开发者

cakePHP class constructors

In normal PHP you can do something like this:

Class Test {
    function __construct($var) {
        echo $var; exit;
    }
}

new Test('Hello World');

So you can pass a variable straight to the constructor. This doesn't seem to work in cakePHP though the variables don't get passed to it. The only way iv managed to do it is do the following:

(component class)

Class TestComponent extends Object {
    function construct($var) {
        echo $var; exit;
    }
}

(controller)

new $this->Test->construct('Hello World');

Is there a better way of doing this more like the开发者_Go百科 first way without having to call the function name directly?


With Components, where are you actually writing new TestComponent($args)?
You don't. You just configure Cake to use a Component, and Cake will instantiate it for you.
You're never actually calling the constructor yourself.

The Cake way to pass parameters to a Component is through the initialize method:

class TestComponent extends Object {
    public function initialize(&$controller, $settings = array()) {
        // use $settings
    }
}

class MyController extends AppController {
    public $components = array('Test' => array(/* your settings */));
}

See http://book.cakephp.org/view/996/Creating-Components.


This is because when you include the component in your controller with the variable $components this already make an instance of the TestComponent class and you don't create instance by yourself.

But after all CakePHP is php you can always create a class, and include it in the controller and use the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜