我写了一个组件,如下所示。
class GoogleApiComponent extends Component {
function __construct($approval_prompt) {
$this->client = new apiClient();
$this->client->setApprovalPrompt(Configure::read('approvalPrompt'));
}
}
我在AppController$components变量中调用它。然后我写了用户控制器如下。
class UsersController extends AppController {
public function oauth_call_back() {
}
}
所以oauth_call_back操作中,我想创建GoogleApiComponent的对象,并调用带有参数的构造函数。如何在CakePHP 2.1中做到这一点?
你可以传递 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 中。当你阅读源代码时,你会惊讶于你会学到什么。