CakePHP Custom Route Classes - How to Pass Argumen

2019-07-27 16:25发布

问题:

I've created a custom route class and I want to be able to pass in settings/options to the constructor so that it's configurable. Can this be done?

Documentation for Custom Route Classes:

http://book.cakephp.org/2.0/en/development/routing.html#custom-route-classes

My custom route class:

https://github.com/Signified/CakePHP-Model-Route-Class

回答1:

You can probably just pass any settings/options you might have in the options of your Router::connect function.

App::import('Lib', 'ModelRoute');
Router::connect('/', array('controller' => 'pages', 'action' => 'display'),
    Array('routeClass' => 'ModelRoute',
          'someMoreOptions' => 'OptionValue' ));

Then you can retrieve the key someMoreOptions in your constructor

public function __construct($settings = array())
    {
        $this->settings = Set::merge($this->settings, $settings);
        // Now you can do something with the option passed.
        if(isset($this->settings['someMoreOptions'])
            DoSomethingWith($this->settings['someMoreOptions']);
    }