在Controller中调用组件构造函数

时间:2012-08-06 13:39:56

标签: php cakephp constructor cakephp-2.1 cakephp-2.2

我写了一个如下组件。

class GoogleApiComponent extends Component {
    function __construct($approval_prompt) {
        $this->client = new apiClient();
        $this->client->setApprovalPrompt(Configure::read('approvalPrompt'));
    }
}

我在AppController的$ components变量中调用它。 然后我写了如下的UsersController。

class UsersController extends AppController {
    public function oauth_call_back() {

    }
}

所以在oauth_call_back动作中,我想创建GoogleApiComponent的对象,并使用参数调用构造函数。 如何在CakePHP 2.1中完成?

1 个答案:

答案 0 :(得分:3)

您可以将Configure :: read()值作为设置属性传递, 或者将构造函数逻辑放在组件的initialize()方法中。

class MyComponent extends Component
{
    private $client;

    public function __construct (ComponentCollection $collection, $settings = array())
    {
        parent::__construct($collection, $settings);
        $this->client = new apiClient();
        $this->client->setApprovalPrompt ($settings['approval']);
    }
}

然后在您的UsersController中写下这个:

public $components = array (
    'My'    => array (
        'approval' => Configure::read('approvalPrompt');
    )
);

或者你可以这样编写你的组件:

class MyComponent extends Component
{
    private $client;

    public function __construct (ComponentCollection $collection, $settings = array())
    {
        parent::__construct($collection, $settings);
        $this->client = new apiClient();
    }

    public function initialize()
    {
        $this->client->setApprovalPrompt (Configure::read('approvalPrompt'));
    }
}

我建议你看一下Component类,它位于CORE / lib / Controller / Component.php中。阅读源代码时,您会对所学内容感到惊讶。

相关问题