Search code examples
phpcakephpcakephp-2.0cakephp-2.3

Adding a custom CakePHP Route


How can i configure a route connection to handle...

/users/{nameofuser_as_param}/{action}.json?limit_as_param=20&offset_as_param=20&order_as_param=created_at

in the routes.php file such that it calls my controller action like...

/users/{action}/{nameofuser_as_param}/{limit_as_param}/{offset_as_param}/{order_as_param}.json?

Note: Iam using Cakephp 2.X


Solution

  • to handle...

    /users/{nameofuser_as_param}/{action}.json

    That's pretty easy, and in the docs.

    Assuming there is a call to parseExtensions in the route file, a route along the lines of this is required:

    Router::connect(
        '/users/:username/:action',
        ['controller' => 'users'],
        [
            'pass' => ['username'],
            // 'username' => '[a-Z0-9]+' // optional param pattern
        ]
    );
    

    The pass key in the 3rd argument to Router::connect is used to specify which of the route parameters should be passed to the controller action. In this case the username will be passed.

    For the rest of the requirements in the question it would make more sense for the action to simply access the get arguments. E.g.:

    public function view($user) 
    {
        $defaults = [
            'limit_as_param' => 0,
            'offset_as_param' => 0,
            'order_as_param' => ''
        ];
    
        $args = array_intersect_key($this->request->query, $defaults) + $defaults;
        ...
    }
    

    It is not possible, without probably significant changes or hacks, to make routes do anything with get arguments since at run time they are only passed the path to determine which is the matching route.