CakePHP at a Glance

CakePHP is designed to make common web-development tasks simple, and easy. Byproviding an all-in-one toolbox to get you started the various parts of CakePHPwork well together or separately.

The goal of this overview is to introduce the general concepts in CakePHP, andgive you a quick overview of how those concepts are implemented in CakePHP. Ifyou are itching to get started on a project, you can start with thetutorial, or dive into the docs.

Conventions Over Configuration

CakePHP provides a basic organizational structure that covers class names,filenames, database table names, and other conventions. While the conventionstake some time to learn, by following the conventions CakePHP provides you canavoid needless configuration and make a uniform application structure that makesworking with various projects simple. The conventions chapter covers the various conventions that CakePHP uses.

The Model Layer

The Model layer represents the part of your application that implements thebusiness logic. It is responsible for retrieving data and converting it into theprimary meaningful concepts in your application. This includes processing,validating, associating or other tasks related to handling data.

In the case of a social network, the Model layer would take care oftasks such as saving the user data, saving friends’ associations, storingand retrieving user photos, finding suggestions for new friends, etc.The model objects can be thought of as “Friend”, “User”, “Comment”, or“Photo”. If we wanted to load some data from our users table we could do:

  1. use Cake\ORM\TableRegistry;
  2.  
  3. $users = TableRegistry::get('Users');
  4. $query = $users->find();
  5. foreach ($query as $row) {
  6. echo $row->username;
  7. }

You may notice that we didn’t have to write any code before we could startworking with our data. By using conventions, CakePHP will use standard classesfor table and entity classes that have not yet been defined.

If we wanted to make a new user and save it (with validation) we would dosomething like:

  1. use Cake\ORM\TableRegistry;
  2.  
  3. $users = TableRegistry::get('Users');
  4. $user = $users->newEntity(['email' => 'mark@example.com']);
  5. $users->save($user);

The View Layer

The View layer renders a presentation of modeled data. Being separate from theModel objects, it is responsible for using the information it has availableto produce any presentational interface your application might need.

For example, the view could use model data to render an HTML view template containing it,or a XML formatted result for others to consume:

  1. // In a view template file, we'll render an 'element' for each user.
  2. <?php foreach ($users as $user): ?>
  3. <li class="user">
  4. <?= $this->element('user_info', ['user' => $user]) ?>
  5. </li>
  6. <?php endforeach; ?>

The View layer provides a number of extension points like View Templates, Elementsand View Cells to let you re-use your presentation logic.

The View layer is not only limited to HTML or text representation of the data.It can be used to deliver common data formats like JSON, XML, and througha pluggable architecture any other format you may need, such as CSV.

The Controller Layer

The Controller layer handles requests from users. It is responsible forrendering a response with the aid of both the Model and the View layers.

A controller can be seen as a manager that ensures that all resources needed forcompleting a task are delegated to the correct workers. It waits for petitionsfrom clients, checks their validity according to authentication or authorizationrules, delegates data fetching or processing to the model, selects the type ofpresentational data that the clients are accepting, and finally delegates therendering process to the View layer. An example of a user registrationcontroller would be:

  1. public function add()
  2. {
  3. $user = $this->Users->newEntity();
  4. if ($this->request->is('post')) {
  5. $user = $this->Users->patchEntity($user, $this->request->getData());
  6. if ($this->Users->save($user, ['validate' => 'registration'])) {
  7. $this->Flash->success(__('You are now registered.'));
  8. } else {
  9. $this->Flash->error(__('There were some problems.'));
  10. }
  11. }
  12. $this->set('user', $user);
  13. }

You may notice that we never explicitly rendered a view. CakePHP’s conventionswill take care of selecting the right view and rendering it with the view datawe prepared with set().

CakePHP Request Cycle

Now that you are familiar with the different layers in CakePHP, lets review howa request cycle works in CakePHP:

Flow diagram showing a typical CakePHP request

The typical CakePHP request cycle starts with a user requesting a page orresource in your application. At a high level each request goes through thefollowing steps:

  • The webserver rewrite rules direct the request to webroot/index.php.
  • Your Application is loaded and bound to an HttpServer.
  • Your application’s middleware is initialized.
  • A request and response is dispatched through the PSR-7 Middleware that yourapplication uses. Typically this includes error trapping and routing.
  • If no response is returned from the middleware and the request containsrouting information, a controller & action are selected.
  • The controller’s action is called and the controller interacts with therequired Models and Components.
  • The controller delegates response creation to the View to generate the outputresulting from the model data.
  • The view uses Helpers and Cells to generate the response body and headers.
  • The response is sent back out through the Middleware.
  • The HttpServer emits the response to the webserver.

Just the Start

Hopefully this quick overview has piqued your interest. Some other greatfeatures in CakePHP are:

Additional Reading