Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Link: A fast and simple PHP Router (github.com/apsdehal)
47 points by apsdehal on May 29, 2014 | hide | past | favorite | 56 comments


The claim of "fast" definitely looks inaccurate in comparison to nikic's router[0]. I'd recommend reading through his blog[1] on the matter.

[0]: https://github.com/nikic/FastRoute

[1]: http://nikic.github.io/2014/02/18/Fast-request-routing-using...


Thanks for your concern, this router is a result out of a effort to learn about routing. I will try to add benchmarks soon.


there are so many php routers these days that any "fast" claims should probably be accompanied by benchmarks.

routing is a fairly uncomplicated task and the speed difference will only become apparent at really high loads.

http://c9s.github.io/Pux/

http://auraphp.com/packages/Aura.Router/

http://zaphpa.org/

http://toroweb.org/

https://github.com/dannyvankooten/PHP-Router

https://github.com/symfony/Routing

http://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Router....


This list is missing https://github.com/nikic/FastRoute which is definitely worth looking at.


I used Epiphany last time I needed something like this. https://github.com/jmathai/epiphany

Note that is more than a router, it's a microframework.


What would you want a 'minimally viable' microframework to include, in terms of functionality?

This has come up a couple of times in PHP framework and router threads, and i've been wondering what it would look like (it would probably be even smaller than Slim Framework). I've gotten as far as including Composer and a rather barebones router and telling people to just include whatever else they want but I suspect other people would want more.

I find it annoying when frameworks include dependencies I don't want, particularly an ORM or a templating engine, but I understand for a lot of people, that's the point (not having to pick dependencies themselves.)


Dont forget µ which is totally a legit router

https://github.com/lastguest/mu


Which begs the question, how on earth do you choose one?

Edit: as in, which router do you pick and how do you pick one? Choice can lead to decision paralysis.


Check whats your need, if you are building up much bigger apps go for a fully fledged framework, rest for small apps you can use microrouters , according to your need, each has its own unique features.


For small apps, you don't need a "router", period. Routing is done by the file system and placing .php files in directories!


One of the benefits of using a url router is access control - you could have a problem with just letting every file be executable by url, especially if you happen to have a remote file inclusion issue anywhere. With a router you know explicitly what can get invoked and what can't.

Although, doing it without a router is probably always going to be faster.


A late trick I discovered, was that you can configure your php instance to inclued a file with every script. For example the following can be added to .htaccess:

  php_value auto_prepend_file 'before.php'
You can then use that for bootstrapping, front controller and to limit access. Can be a bit clumsy, but it's nicely divorced from simple page controllers.


neat! this beats putting an include at the top of each file...


It certainly does.

I personally would still prefer a router but I know of a project which was written almost entirely in sprawling, procedural PHP that might benefit from this. Although I do wonder what the performance hit would be.


the fact that it uses the magic __callStatic probably means it's out of the running for "fastest"


I liked Klein.php as well. https://github.com/chriso/klein.php



Why would you want to use any PHP router instead of writing the rewrite rules within an Apache VirtualHost file or a .htaccess file?


Separation of concerns? Why would I ever want to implement business logic in an http server configuration file?


Umm.. what do you think a server is for?


The http server's job is to translate URLs into http requests for consumption by the application. The http server should generally be agnostic regarding the semantic meaning of your URLs, which take the form of business rules, the proper place for which is the application layer (whenever possible).


At a guess because you don't use apache, you don't have .htaccess / conf permissions, you are going to distribute your script and can't rely on the above, your router uses database or other external sources, you want to be like the cool kids, or because you want to, it works, and why not?


Let's say you are using Apache (so maybe that already means you're not one of the cool kids?), then why would you use any of the available PHP routers?

Overall, I'm not trying to discount anyone's work with developing PHP routers, but I'd like to understand the benefits of using them.


It would help decouple your application code and structure from Apache configuration and the need to be familiar with Apache configuration syntax and nuance. Your Apache config would just need to route all requests to your app root to one routing file, which is pretty simple, and then the routing file can process from there. You'd also have the benefits of more configurable routing, if you needed that (e.g. routing based on specific parameters in a POST instead of just based on the request url and method).


I would prefer to have all my behavior be in my codebase.

Also, restarting Apache after adding a route would get tedious during development.


I guess you are asking why not just use the filesystem one-one like mapping url to file?

A benefit of routing is that you can have a single point of contact in your app: a front controller. And you can place your route config in one place.

This router also has RESTful routing, detecting HTTP methods upfront that correspond to a predictable method name in a named class.


Do you have experience with massive http conf files? They become very hard to maintain! There is always going to be tradeoffs between maintainability, speed and ease of use. It just depends what sort of application you are running.


FWIW at Etsy I built and subsequently helped completely dismantle a minimal PHP routing framework. We just used .htaccess and php files.

PHP/Apache affords you a fast, simple alternative, and what you gain with a framework (route lookup for an object) just isn't compelling enough IMO to justify the added overhead and complexity.

I think the endless proliferation of PHP microrouters (including mine, RIP) is people porting Django and Rails features to PHP without applying critical thinking first. (Myself included.)


How complicated were the Etsy routes? And were the added overhead and complexity?

And I know it is a pain to restart Apache each time there's a change to the configuration file, but does anyone know the time differences between a PHP router and Apache rewrites?


Basically just "/listing/<a number>/<some ignored text> goes to listing.php", multiplied by a thousand pages or so.

There's overhead associated with doing the bookkeeping necessary to compute the route lookups. In practice, it's not that awful to just write a function like "get_url($listing_id)" by hand, and debugging this later is much more straightforward.

We didn't need to restart httpd (in development at least) to add to .htaccess. For production deploys maybe we were configured to do this, but that's hidden from development.


Put it in .htaccess. No restarts needed.


That's correct - I was thinking of using an Apache VirtualHost file. (Isn't using the .htaccess file slower(?) than using the VirtualHost file?)


It is slower, since .htaccess is parsed on every request. (However, it is probably faster than routing through PHP code.)


You can reload Apache without a restart (apache2/httpd graceful/reload depending on your distro).


then I think what would be best here is a command line tool to manage your routes on .htaccess or nginx configs.


Looks like everyone and their grandma has written their own PHP router.

Here's mine:

https://github.com/erming/route

Code: https://github.com/erming/route/blob/master/route.php

~80 LOC


I did. It's not worth posting though.

I think writing a php router is one of those things everyone who works with php should learn to do. It teaches you a lot.


Meh, another PHP library using lengthy static methods making it impossible to extend.


Yeah I don't understand the use of statics here. I'm going to guess it's just so they can use the "nicer" syntax without having to instantiate a new object, which would honestly make more sense to me. That way you can inject a Link instance into your controller/views and just call `$link->route('namedRoute')`.


It looks tidier with the global.


How does this compare with something like Slim?

+1 for being lightweight and readable.


Slim is a whole (micro)frameork that includes routing. This is just a request router.


Nice work! A micro-micro-framework, makes Slim and Silex look big.


It is nice, but having implemented something like this myself at work recently, this looks eerily familiar and some things about it bug me.

For example, why is ReflectionClass not used (I'm guessing PHP 4 compatibility)? Particularly because class_exists can cause major headaches if you use the default autoloader, see https://bugs.php.net/bug.php?id=52339

There's also little information available from outside the router; an invalid class/method uses die without giving you an option to check for it and handle it some other way. I also don't immediately see any special handling for not allowing magical methods to be called

Definitely a good start for personal projects though, just needs some spit and polish


Thanks for your concern, I would try to implement features you have said, Its still under development mode and needs much polish.


Good luck! Another feature of my router is that the method name converts snake_case to camelCase, so that resource/list_actions calls ResourceController::listActions(), but some of the features I mention will most likely incur a performance hit, but it shouldn't be significant once opcache comes into play


Is it a PHP thing to indent with tabs rather than 2 spaces? Genuinely curious.


The community-organized PSR-2 standard [1], used by every major framework and open-source package, states:

> Code MUST use 4 spaces for indenting, not tabs

[1] http://www.php-fig.org/psr/psr-2/


Nope, it's a ruby thing I believe.


or maybe it's a javascript thing http://code.jquery.com/jquery-2.1.1.js

or maybe it's just a trolling thing.


No tests?


Its under development, much to be added. Thanks for your concern.


It's written in PHP.


Your nick should read prejudice.


Which is readily unit tested.


Yes because no other PHP projects have perfectly good unit tests. /s




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: