I’ve got a couple of messages from [apparently] junior programmers regarding my previous post, so I decided to go back and explain some of the magic that’s happening every day inside Cake applications.
As you know (or should have known) Cake does a lot of magic behind the scenes, as long as we’re following some naming conventions. The developers prefer convention over configuration (via files), which may seem a bit restrictive for some, but, once you get used to it, you will notice that it speeds up things.
If you recall from the previous post, the User Model looks like this:
class User extends AppModel {
var $name = 'User';
}
This class extends a class named “AppModel“, which in turn extends a class named “Model“. Therefore, each method described in the Model class is also available to the AppModel and (our own) the User class in turn.
Why did the developers go so far as to create two classes instead of one? Simply because they wanted to give us more flexibility. We have the option to create a class called AppModel and place that code inside the app directory like this:
/**
*
* Filename: /app/app_model.php
*
**/
class AppModel extends Model {
}
Now, whenever you create this file, you can add your own custom functions, which will be available to all your models. The same goes for all your controllers, i.e. you can create a file named app_controller.php and place it inside your app directory, where a class named AppController will extend the Controller class.
In case you didn’t figure it out yourself by now, there is a file named app_model.php which Cake uses if you haven’t created your own (take a look at /cake/lib/model). Cake automatically includes your own app_model.php if you have one, or its own (empty) version if you don’t. Talking about some serious magic here!
In general, whenever your application runs, all requests are redirected to the index.php file, which in turn includes all necessary files. Cake examines your app directory and, if it finds files which can override its core files, it includes those files instead.
Finally, if you follow the naming conventions mentioned earlier, you won’t have to include anything in your files (there are some exceptions to this rule, if you need a certain level of complexity). For instance, if you name your model User, that model will be automatically available in your UsersController controller, simply by typing $this->User.
Catch you all next time.
