CakePHP - how can I conditionally load a component into a controller?

I am using the excellent Facebook plugin for cakephp 1.3 http://www.webtechnick.com . This is what I have at the moment:

class UsersController extends AppController { var $name = 'Users'; var $components = array('Facebook.Connect'); function beforeFilter { $this->set('facebookUser', $this->Connect->user()); } } 

But I want to download the Facebook.Connect component conditionally and use it in the controller - something like this in sudocode ...

 if ($thisIsTrue) { Load_the_component_and_make_it_ready_for_use; $this->set('facebookUser', $this->Connect->user()); } 

How can I do it?

+4
source share
5 answers

Since the component is initialized when loading from the controller, I would not recommend downloading it later.

As maggie commented, you can download the component ( http://book.cakephp.org/view/939/Loading-Components ), but then you have to invoke the launch and initialize yourself and attach the object to your controller.

In general, it might be easier to just make the $ this-> set ... conditional parameter and load the component each time.

+4
source

If you do this in CakePHP 2.0, it is very simple. I found this SO thread, which initially discouraged me, but this should be a problem with 1.3 and below. For instance:

 public function beforeFilter(){ parent::beforeFilter(); $this->Paypal = $this->Components->load('Paypal'); } 

And all that she wrote.

+5
source

If something is missing there, you use App :: import to import the component.

I heard that you don’t want to do this with models, because there are other things that are thought of. But the components should be fine.

 if( $condition ) { App::import( 'Component', 'MyComponent' ); $this->MyComponent = new MyComponent(); $this->MyComponent->method(); } 

NTN, Travis

+3
source

I know this is already late, but for those who are looking for how to do this, you need to add it to your __construct before you call Parent __construct.

So you would do something like this:

 function __construct(){ if($thisIsTrue){ $this->components[] = 'Facebook.Connect' } parent::__construct(); } 

You can do this in your individual controllers or in app_controller so that each controller selects it.

The only problem I ran into was that it was so hard to get variables for the if () operator so early. In my example, I only need the component if I were on the admin page, and instead of checking the parameters of $ this-> params, I had to check the URL from $ _SERVER.

I found this solution here, but he said that you need to do this in app_controller, which is not so: Loading the conditional component in CakePHP

+2
source

try this in your controller

 var $components = array("Email", "Session", 'RequestHandler', 'Cookie'); 
0
source

All Articles