1

Is it necessary to declare the name variable in models and controllers? Or just good practice? For example:

class User extends AppModel {
    public $name = 'User';
}

class UsersController extends AppController {
    public $name = 'Users';
}

2 Answers 2

2

Cake does that internally when you don't specify it based on the class name.

However, this leads into a nice trap: When extending a model or controller the name is not constructed again. So you'll have to specify the name to make it work right. This is important because other things like view file folder, modelClass and in models alias depend on the name being correct.

So no it is not required until you extend a class.

In models pay attention when dealing with data: Models use Model::$alias not $name for that. The reason for that are associations. If Code hasMany Programmer but Programmer is your User model the alias is used and the alias is Programmer, not User. So use the alias in models when you do something like $this->data[$this->alias]['field'].

1
  • Can you give me an example of extending a class? We are already extending the model to the AppModel and the controller to the AppController.
    – David Cole
    Oct 22, 2014 at 16:30
0

the most important that I see, cakephp use the public name in the querys, querys take the public Variable name = 'User'; Fields then bring data of the table User, will be appointed User.id as User_id, and if you change in the variable public name 'User'; then you will see how this affects.

Mainly used when developers do not follow correctly the letter lan cakephp conventions, or in my case, which at first did not understand very well how to use the conventions of cake php when words are not monosyllables. Then affects your querys and your data. To heal that part had to use public name.

2
  • Thank you for your answer, I had been pondering this for quite some time.
    – David Cole
    Oct 22, 2014 at 19:40
  • This is plain wrong. Models use Model::$alias not $name for that. The reason for that are associations. If Code hasMany Programmer but programmer is your User model the alias is used and the alias is Programmer. So use the alias in models when you do something like $this->data[$this->alias]['field'].
    – floriank
    Oct 22, 2014 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.