CakePHP
01 / 02

Conventions, Controllers & the ORM

CakePHP: Conventions, Controllers & the ORM

CakePHP is a mature MVC framework for PHP built around convention-over-configuration: a table articles maps by default to an Articles model and ArticlesController, reducing the explicit configuration needed for common patterns.

Controllers

<?php
// src/Controller/AppController.php -- base class every controller extends,
// shared setup lives here instead of duplicated per-controller
namespace App\Controller;

use Cake\Controller\Controller;

class AppController extends Controller
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Flash');
        $this->loadComponent('Authentication.Authentication');
    }
}

// src/Controller/ArticlesController.php
namespace App\Controller;

class ArticlesController extends AppController
{
    public function index()
    {
        // Eager-load Authors -- avoids an N+1 query per article
        $articles = $this->Articles->find()->contain(['Authors']);
        $this->set(compact('articles'));
    }

    public function add()
    {
        $article = $this->Articles->newEmptyEntity();
        if ($this->request->is('post')) {
            $article = $this->Articles->patchEntity($article, $this->request->getData());
            if ($this->Articles->save($article)) {
                $this->Flash->success('Article saved.');
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error('Could not save article.');
        }
        $this->set(compact('article'));
    }
}

Table, Entity & Associations

<?php
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        $this->addBehavior('Timestamp'); // auto-manages created/modified

        $this->belongsTo('Authors');
        $this->belongsToMany('Tags');
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->requirePresence('title')
            ->notEmptyString('title')
            ->maxLength('title', 255);

        return $validator;
    }
}

// src/Model/Entity/Article.php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Article extends Entity
{
    protected $_accessible = ['title' => true, 'body' => true, 'author_id' => true];
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free