Which models can I access from a controller in CakePHP?

Suppose I have the classic Post model and I've created an Author model too.

I have some basic questions:

  1. The Post object is automatically created whithin the PostsController?

  2. In order to create an instance of Post whithin AuthorsController, is the only way with

$this->Post = ClassRegistry::init('Post');

Please notice that by doing " $this->Post " I assume the Post variable will be created in this line. Am I right ?

Thank you in advance!

Upvotes: 0

Views: 74

Answers (2)

AD7six
AD7six

Reputation: 66299

All models in your uses array

You can access $this->MmodelName for all models declared in the uses property - If this property is not declared it defaults to the model corresponding to the controller - i.e. PostsContorller -> Post model.

Models declared in $uses as created/instanciated on first reference - i.e. they are lazily created.

Upvotes: 0

swiecki
swiecki

Reputation: 3483

Look into model associations. If your associations are set up properly, you will be able to do

$this->Author->Post

to access the Post model from the Authorscontroller. If the model was not related but you still needed to access it, you could do so using the $uses array.

In terms of your first question, you are correct. All of your controllers extend Appcontroller which imports the default cake Controller class found in /lib/. You can see on line 376 in the cakePHP controller file here that the model whose name is equal to the class name is loaded, after all of the models given in the $uses array are loaded.

Upvotes: 4

Related Questions