Reputation: 927
I have written a component as below.
class GoogleApiComponent extends Component {
function __construct($approval_prompt) {
$this->client = new apiClient();
$this->client->setApprovalPrompt(Configure::read('approvalPrompt'));
}
}
I am calling this in $components variable of AppController. Then I have written UsersController as below.
class UsersController extends AppController {
public function oauth_call_back() {
}
}
So in oauth_call_back action I wanna create object of GoogleApiComponent and also call the constructor with parameter. How to do it in CakePHP 2.1?
Upvotes: 0
Views: 1409
Reputation: 1690
You can pass the Configure::read() value as a setting property, or put the constructor logic within the initialize() method of your component.
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']);
}
}
And then write this in your UsersController:
public $components = array (
'My' => array (
'approval' => Configure::read('approvalPrompt');
)
);
Or you may write your component as such:
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'));
}
}
I would recommend you to have a look at the Component class, which is within CORE/lib/Controller/Component.php. You'd be surprised of what you'll learn when you read the source code.
Upvotes: 3