Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to load models in CakePHP 2.0

Tags:

I'm not sure of the best way to load models in CakePHP 2.0 now.


Question 1

I have a model where more than one database field is related to another model.

customers table has the fields country_origin, country_residence and country_study and all of those fields contain an ID from the table countries.

So in my Customer model, how am I supposed to load the Country model?


Question 2

Has Controller::loadModel() been deprecated or is it bad practice to use this? How am I supposed to load a model in the controller?


Question 3

When or why do you have to use App::uses() in a controller or model? I don't understand the point when the models will load anyway if you use the normal methods like loadModel(), hasOne, hasMany, belongsTo, etc.

like image 344
BadHorsie Avatar asked Mar 06 '12 12:03

BadHorsie


2 Answers

This should be simple to understand. If you are using a controller and you need to load another model, you can call:

$this->loadModel('SomeModel'); 

Then you can make calls to the model like you normally would:

$this->SomeModel->read(null, '1'); 

App::uses is for lazy loading of classes. So you can still load a model using uses:

App::uses('MyModel', 'Model'); 

But then you will need to call it differently:

$MyModel = new MyModel(); $MyModel->read(null, '1'); 

or

MyModel::read(null, '1'); 

It just depends on where and how you want to use it.

like image 82
Chuck Burgess Avatar answered Sep 27 '22 19:09

Chuck Burgess


The preferred way is

$this->load('MyModel'); 

However, you can also use

public $uses = array('DefaultModel', 'MyModel'); . . $this->MyModel->field(...); 

Cake supports both and you are free to use anyone you like.

like image 38
ayudh_das Avatar answered Sep 27 '22 18:09

ayudh_das