Chobeat
Chobeat

Reputation: 3535

Cakephp: add a model to $uses at runtime

I need to write a modular function that could work with any kind of controller. I need, at runtime, to do something like.

$tools=array("a","b","c");
foreach($tools as $tool{
   ...
   //here there should be something like add_to_$uses($tool)
   $this->{$tool}->find();

Obviously simply adding the item to $this->uses doesn't work. How am I supposed to do this?

Upvotes: 0

Views: 459

Answers (2)

gustavotkg
gustavotkg

Reputation: 4399

I think what you need is loadModel method.

$tools=array("a","b","c");
foreach($tools as $tool) {
   // ...
   $this->loadModel($tool);
   $this->{$tool}->find();
}

More info in CakePHP's Book

Upvotes: 3

Scott Harwell
Scott Harwell

Reputation: 7465

I'm not aware of a way to load a model to a controller at runtime. Basically, you need to add all the models you might ever use to the controller's $uses array.

However, if the models are associated to another model in your uses array, then you can bind them at runtime in the controller:

$this->Model1->bind(
    'hasOne' => array(
        'Model2'
    )
);

You can change the hasOne to the type of relationship for your model. You can also add as many models as you want.

The converse of this is unbind.

Upvotes: 0

Related Questions