Dennis
Dennis

Reputation: 1951

cakephp routes modify controllers name / fetching controllers name

I created a route which is analog to this one:

Router::connect("/backend/:controller/:action/*");

And now I want to route every controller that fits this pattern to be renamed to something like backend_:controller.

Somehow like that:

Router::connect("/backend/:controller/:action/*", array('controller' => 'backend_:controller'));

Example: If the URL www.example.com/backend/settings/myaction is called, it would route to the controller "backend_settings" and invoke the action "myaction"!

But on the other hand, if some called www.example.com/settings, it would route to the controller "settings".

The URL is supposed to stay the way it was called, cakePHP should only use a modified controller name!

I hope someone can point me to the best solution I am supposed to use for this problem. Thanks in advance!

Upvotes: 3

Views: 1964

Answers (2)

clns
clns

Reputation: 2304

You can use the routeClass property when specifying your route, and use a custom route class.

This is my implementation of the CakeRoute class that does exactly what you described (appends a controller prefix to your controller):

// ControllerPrefixRoute.php file in app/Routing/Route/

App::uses('CakeRoute', 'Routing/Route');

class ControllerPrefixRoute extends CakeRoute {

    /**
     * Parses a string url into an array. If a controller_prefix key is found it will be appended to the
     * controller parameter
     *
     * @param string $url The url to parse
     * @return mixed false on failure, or an array of request parameters
     */
    public function parse($url) {

        $params = parent::parse($url);

        if (!$params) {
            return false;
        }
        $params['controller'] = $params['controller_prefix'].'_'.$params['controller'];
        return $params;
    }

}

And here is how to use it:

// inside routes.php file in app/Config/

App::uses('ControllerPrefixRoute', 'Routing/Route');

Router::connect("/:controller_prefix/:controller/:action/*", array(), array('routeClass' => 'ControllerPrefixRoute'));

So this url /backend/settings/myaction will invoke BackendSettingsController::myaction

Upvotes: 5

pleasedontbelong
pleasedontbelong

Reputation: 20102

maybe what you need is a router prefix.

go to the core.php and add this line:

Configure::write('Routing.prefixes', array('backend'));

and that's all... you don't need to add routes.. so now www.example.com/backend/settings/add will look for a method called backend_add() in the Settings controller

And www.example.com/settings/add will call the method called add() in the Settings controller

here you'll find better examples =)

hope this helps

Upvotes: 1

Related Questions