Database Access & ORM
In CakePHP working with data through the database is done with two primary objecttypes. The first are repositories or table objects. These objectsprovide access to collections of data. They allow you to save new records,modify/delete existing ones, define relations, and perform bulk operations. Thesecond type of objects are entities. Entities represent individual recordsand allow you to define row/record level behavior & functionality.
These two classes are usually responsible for managing almost everythingthat happens regarding your data, its validity, interactions and evolutionof the information workflow in your domain of work.
CakePHP’s built-in ORM specializes in relational databases, but can be extendedto support alternative datasources.
The CakePHP ORM borrows ideas and concepts from both ActiveRecord and Datamapperpatterns. It aims to create a hybrid implementation that combines aspects ofboth patterns to create a fast, simple to use ORM.
Before we get started exploring the ORM, make sure you configure yourdatabase connections.
Quick Example
To get started you don’t have to write any code. If you’ve followed the CakePHPconventions for your database tablesyou can just start using the ORM. For example if we wanted to load some data from our articles
table we could do:
- use Cake\ORM\TableRegistry;
- $articles = TableRegistry::getTableLocator()->get('Articles');
- $query = $articles->find();
- foreach ($query as $row) {
- echo $row->title;
- }
Note that we didn’t have to create any code or wire any configuration up.The conventions in CakePHP allow us to skip some boilerplate code and allow theframework to insert base classes when your application has not createda concrete class. If we wanted to customize our ArticlesTable class adding someassociations or defining some additional methods we would add the following tosrc/Model/Table/ArticlesTable.php after the <?php
opening tag:
- namespace App\Model\Table;
- use Cake\ORM\Table;
- class ArticlesTable extends Table
- {
- }
Table classes use the CamelCased version of the table name with the Table
suffix as the class name. Once your class has been created you get a referenceto it using the ORM\Locator\TableLocator
through ORM\TableRegistry
as before:
- use Cake\ORM\TableRegistry;
- // $articles is an instance of our ArticlesTable class.
- $articles = TableRegistry::getTableLocator()->get('Articles');
Now that we have a concrete table class, we’ll probably want to use a concreteentity class. Entity classes let you define accessor and mutator methods, definecustom logic for individual records and much more. We’ll start off by adding thefollowing to src/Model/Entity/Article.php after the <?php
opening tag:
- namespace App\Model\Entity;
- use Cake\ORM\Entity;
- class Article extends Entity
- {
- }
Entities use the singular CamelCase version of the table name as their classname by default. Now that we have created our entity class, when weload entities from the database we’ll get instances of our new Article class:
- use Cake\ORM\TableRegistry;
- // $articles is an instance of ArticlesTable.
- $articles = TableRegistry::getTableLocator()->get('Articles');
- $query = $articles->find();
- foreach ($query as $row) {
- // Each row is now an instance of our Article class.
- echo $row->title;
- }
CakePHP uses naming conventions to link the Table and Entity class together. Ifyou need to customize which entity a table uses you can use theentityClass()
method to set a specific classname.
See the chapters on Table Objects and Entities for moreinformation on how to use table objects and entities in your application.
More Information
- Database Basics
- Query Builder
- Table Objects
- Entities
- Retrieving Data & Results Sets
- Debugging Queries and ResultSets
- Getting a Single Entity by Primary Key
- Using Finders to Load Data
- Getting the First Result
- Getting a Count of Results
- Finding Key/Value Pairs
- Finding Threaded Data
- Custom Finder Methods
- Dynamic Finders
- Retrieving Associated Data
- Eager Loading Associations Via Contain
- Filtering by Associated Data Via Matching And Joins
- Changing Fetching Strategies
- Lazy Loading Associations
- Working with Result Sets
- Modifying Results with Map/Reduce
- Validating Data
- Saving Data
- Deleting Data
- Associations - Linking Tables Together
- Behaviors
- Schema System
- Schema Cache Tool