Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Tables and entities

The ORM is the part of the framework that lets you work with the database through PHP objects instead of SQL queries. In CakePHP every table has two classes: the table class runs queries and saves data, and the entity class represents one row of the table.

Where they live

ClassFileResponsible for
ArticlesTablesrc/Model/Table/ArticlesTable.phpFinding, saving, deleting
Articlesrc/Model/Entity/Article.phpOne article and its fields

Creating

bin/cake bake model Articles

The command reads the columns of the articles table from the database and creates both files. The table must already exist; the migration created it.

The table class

// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;
 
use Cake\ORM\Table;
 
class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);
 
        $this->addBehavior('Timestamp');
    }
}

Columns are not listed: the ORM learns them from the database. The addBehavior('Timestamp') line tells the framework to fill in created and modified. The generator also adds validation rules to the file; they have a separate lesson.

The entity class

// src/Model/Entity/Article.php
namespace App\Model\Entity;
 
use Cake\ORM\Entity;
 
class Article extends Entity
{
    protected array $_accessible = [
        'title' => true,
        'body' => true,
        'published' => true,
    ];
}

$_accessible lists the fields that may be filled with form data. Columns are available as properties: $article->title.

Using it in a controller

In ArticlesController the table is available as $this->Articles; the framework finds it by the controller name:

// src/Controller/ArticlesController.php
public function index(): void
{
    $articles = $this->Articles->find()->all();
 
    $this->set(compact('articles'));
}
<ul>
    <?php foreach ($articles as $article): ?>
        <li><?= h($article->title) ?></li>
    <?php endforeach; ?>
</ul>

Open /articles and the titles of the articles added by the seed appear. Each list item is an object of the Article class.

The table elsewhere

In another controller or in a command the table is obtained by name:

$articles = $this->fetchTable('Articles');

A computed field

The entity class can describe a field that does not exist in the table:

// src/Model/Entity/Article.php
protected function _getExcerpt(): string
{
    return mb_substr($this->body, 0, 100) . '…';
}

A method with the _get prefix becomes a property: $article->excerpt returns the first hundred characters of the text.

Common mistake

The table saves and deletes, not the entity: there is no $article->save() method. The correct call is $this->Articles->save($article). An entity holds data and a table works with the database.

Thanks for reading!

Donate to the site — we work hard for you.