Skip to content

Instantly share code, notes, and snippets.

@romaninsh
Created April 4, 2013 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romaninsh/5313222 to your computer and use it in GitHub Desktop.
Save romaninsh/5313222 to your computer and use it in GitHub Desktop.

Pattern Router

A typical Agile Toolkit application converts your URL into a page. For example /mysite/profile?id=123 normally could be implemented like this:

class page_profile extends Page {
     function init(){
         parent::init();
         $this->setModel('User')->load($_GET['id']);
     }
     function defaultTemplate(){
         return array('page/profile');
     }
}

To send user to this page, you would use $api->url('profile',array('id'=>'123'));

Pattern Router is an API controller which can make some arguments part of your URL. To make my example appear nicer you would add the following to your API::init:

$this->add('Controller_PatternRouter')
    ->link('profile',array('id'))
    ->route();

This code would change behavior of your application in two ways:

* /mysite/profile/123 will now be routed to the profile, but would still contain $_GET['id']=123
* $api->url('profile',array('id'=>123)); will now produce the new URL format.

The best part, of course, is that everything happens magically and you don't need to do any changes in your code. Another great thing is that you can still send other arguments to the page or omit the ID and all of this would still work perfectly.

Router supports multiple arguments and can also perform regular-expression check so that your profile/edit wouldn't accidentally be considered.

This functionality is already part of Agile Toolkit master

Pattern router contains alternative "rule" implementation, which I think is too complex and I'm thinking of dropping it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment