2012-08-06 80 views
0

我写了一个组件,如下所示。调用控制器中的组件构造函数

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中做到这一点?

回答

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内。当你阅读源代码时,你会惊讶于你会学到什么。