how to set default prefix in controller -> skip defining prefix in links

690 Views Asked by At

I have the following idea: I'd like to be able to define the default prefix in any given controller. So let's say the default prefix for the CitiesController implements all actions with the "admin" prefix ("admin_index", "admin_add", etc.), but the ProvincesController implements all actions with the

"superadmin" prefix ("superadmin_index", "superadmin_add", etc.)

The problem with this is, every time I want to link to any "city stuff", I have to specify "admin" => "true". Any time I want to link to any "province stuff", I have to specify

"superadmin" => "true".

That's already quite a bit of work initially, but if I decided I wanted to change the prefix from "admin" to "superadmin" for cities, it would be even more work.

So I was wondering if there's to somehow do something along the lines of:

class CitiesController extends AppController {
    var $defaultPrefix = "admin"
}

And then in the HTML helper link function, do something like:

class LinkHelper extends AppHelper {

    public $helpers = array('Html');

    function myDynamicPrefixLink($title, $options) {
        // check whether prefix was set (custom function that checks all known prefixes)
        if (! isPrefixSet($options)) {
            // no clue how to get the controller here
            $controller = functionToGetControllerByName($options['controller']);

            // check whether controller has a defined default prefix 
            $prefix = $controller->defaultPrefix;
            if ($prefix) {
                // set the given prefix to true
                $options[$prefix] = true;
            }

        // use HTML helper to get link
        return $this->Html->link($title, $options);
    }
}

I just have no clue how to get from the helper to the controller of the given name dynamically.

Another option would be to store the default prefix somewhere else, but for now I feel that the best place for this would be in any given controller itself.

Another idea would be to even have that look up function dependent on both, the controller and the action, and not just the controller.

1

There are 1 best solutions below

0
On

You should be able to use the Router::connect to supply defaults (see code and documentation on Github: link) to specify default prefixes for certain controllers and even actions.

However, if you want more flexibility than the current Router provides, you can extend your use of the Router::connect by specifying an alternate Route class to use:

Router::connect(
    '/path/to/route',
    array('prefix' => 'superadmin'),
    array('routeClass' => 'MyCustomRouter')
);

Examples of this can be seen in the CakePHP documentation.