05 Jul 2008 16:06
TAGS: dev django php regexp route
As I've recently work with Django, the way it does the URL-based routing seemed really cool for me. I missed that in PHP, so I decided to code something like this.
Here is a class that uses (extends) my Controller class that does the routing:
class Controller_Ajax_Auth extends Controller_Ajax { protected $routes = Array( ':^info$:' => 'info', ':^challenge$:' => 'challenge', ':^login$:' => 'login', ':^logout$:' => 'logout', ); protected function info($url) { $r = Array(); /* something */ $this->ajaxResponse($r); } protected function challenge($url) { /* $q = something */ $this->ajaxResponse($q); } protected function login($url) { /* set $auth to true if logged */ $this->ajaxResponse($auth); } protected function logout($url) { /* logout */ $this->ajaxResponse(null); } }
This mainly routes URLs info, challenge, login and logout to corresponding methods in the same object.
But you can route out of the object to other Controller subclass instance:
protected $routes = Array(
':^auth/(.*)$:' => 'Controller_Ajax_Auth',
);
This gets URL and passes what's after auth/ to the new object of class Controller_Ajax_Auth (see the code above). Generally the first ()s in the left side of each line define what's passed to the method/object on the right side.
The controller has abstract errorHandler and defaultAction methods that need to be overridden. The first is called when a exception is thrown in a performed action. The latter is called, when routing comes to some object and then no routing line matches.
Post preview:
Close preview