2012-08-06 29 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內。當你閱讀源代碼時,你會驚訝於你會學到什麼。