Entities

  • class Cake\ORM\Entity

While Table Objects represent and provide access to a collection ofobjects, entities represent individual rows or domain objects in yourapplication. Entities contain methods to manipulate andaccess the data they contain. Fields can also be accessed as properties on the object.

Entities are created for you each time you use find() on a tableobject.

Creating Entity Classes

You don’t need to create entity classes to get started with the ORM in CakePHP.However, if you want to have custom logic in your entities you will need tocreate classes. By convention entity classes live in src/Model/Entity/. Ifour application had an articles table we could create the following entity:

  1. // src/Model/Entity/Article.php
  2. namespace App\Model\Entity;
  3.  
  4. use Cake\ORM\Entity;
  5.  
  6. class Article extends Entity
  7. {
  8. }

Right now this entity doesn’t do very much. However, when we load data from ourarticles table, we’ll get instances of this class.

Note

If you don’t define an entity class CakePHP will use the basic Entity class.

Creating Entities

Entities can be directly instantiated:

  1. use App\Model\Entity\Article;
  2.  
  3. $article = new Article();

When instantiating an entity you can pass the fields with the data you wantto store in them:

  1. use App\Model\Entity\Article;
  2.  
  3. $article = new Article([
  4. 'id' => 1,
  5. 'title' => 'New Article',
  6. 'created' => new DateTime('now')
  7. ]);

The preferred way of getting new entities is using the newEmptyEntity() method from theTable objects:

  1. use Cake\ORM\TableRegistry;
  2.  
  3. $article = TableRegistry::getTableLocator()->get('Articles')->newEmptyEntity();
  4.  
  5. $article = TableRegistry::getTableLocator()->get('Articles')->newEntity([
  6. 'id' => 1,
  7. 'title' => 'New Article',
  8. 'created' => new DateTime('now')
  9. ]);

$article will be an instance of App\Model\Entity\Article or fallback toCake\ORM\Entity instance if you haven’t created the Article class.

Accessing Entity Data

Entities provide a few ways to access the data they contain. Most commonly youwill access the data in an entity using object notation:

  1. use App\Model\Entity\Article;
  2.  
  3. $article = new Article;
  4. $article->title = 'This is my first post';
  5. echo $article->title;

You can also use the get() and set() methods:

  1. $article->set('title', 'This is my first post');
  2. echo $article->get('title');

When using set() you can update multiple fields at once using an array:

  1. $article->set([
  2. 'title' => 'My first post',
  3. 'body' => 'It is the best ever!'
  4. ]);

Warning

When updating entities with request data you should whitelist which fieldscan be set with mass assignment.

You can check if fields are defined in your entities with has():

  1. $article = new Article([
  2. 'title' => 'First post',
  3. 'user_id' => null
  4. ]);
  5. $article->has('title'); // true
  6. $article->has('user_id'); // false
  7. $article->has('undefined'); // false.

The has() method will return true if a field is defined and hasa non-null value. You can use isEmpty() and hasValue() to check ifa field contains a ‘non-empty’ value:

  1. $article = new Article([
  2. 'title' => 'First post',
  3. 'user_id' => null
  4. ]);
  5. $article->isEmpty('title'); // false
  6. $article->hasValue('title'); // true
  7.  
  8. $article->isEmpty('user_id'); // true
  9. $article->hasValue('user_id'); // false

Accessors & Mutators

In addition to the simple get/set interface, entities allow you to provideaccessors and mutator methods. These methods let you customize how fieldsare read or set.

Accessors use the convention of _get followed by the CamelCased version ofthe field name.

  • Cake\ORM\Entity::get($field)

They receive the basic value stored in the _properties arrayas their only argument. Accessors will be used when saving entities, so becareful when defining methods that format data, as the formatted data will bepersisted. For example:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class Article extends Entity
  6. {
  7. protected function _getTitle($title)
  8. {
  9. return ucwords($title);
  10. }
  11. }

The accessor would be run when getting the field through any of these two ways:

  1. echo $article->title;
  2. echo $article->get('title');

Note

Code in your accessors is executed each time you reference the field. You canuse a local variable to cache it if you are performing a resource-intensiveoperation in your accessor like this: $myEntityProp = $entity->my_property.

You can customize how fields get set by defining a mutator:

  • Cake\ORM\Entity::set($field = null, $value = null)

Mutator methods should always return the value that should be stored in thefield. As you can see above, you can also use mutators to set othercalculated fields. When doing this, be careful to not introduce any loops,as CakePHP will not prevent infinitely looping mutator methods.

Mutators allow you to convert fields as they are set, or create calculateddata. Mutators and accessors are applied when fields are read using propertyaccess, or using get() and set(). For example:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4. use Cake\Utility\Text;
  5.  
  6. class Article extends Entity
  7. {
  8. protected function _setTitle($title)
  9. {
  10. return Text::slug($title);
  11. }
  12. }

The mutator would be run when setting the field through any of these twoways:

  1. $user->title = 'foo'; // slug is set as well
  2. $user->set('title', 'foo'); // slug is set as well

Warning

Accessors are also run before entities are persisted to the database.If you want to transform fields but not persist that transformation,we recommend using virtual fields as those are not persisted.

Creating Virtual Fields

By defining accessors you can provide access to fields that do notactually exist. For example if your users table has first_name andlast_name you could create a method for the full name:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class User extends Entity
  6. {
  7. protected function _getFullName()
  8. {
  9. return $this->first_name . ' ' . $this->last_name;
  10. }
  11. }

You can access virtual fields as if they existed on the entity. The propertyname will be the lower case and underscored version of the method (full_name):

  1. echo $user->full_name;

Do bear in mind that virtual fields cannot be used in finds. If you wantthem to be part of JSON or array representations of your entities,see Exposing Virtual Fields.

Checking if an Entity Has Been Modified

  • Cake\ORM\Entity::dirty($field = null, $dirty = null)

You may want to make code conditional based on whether or not fields havechanged in an entity. For example, you may only want to validate fields whenthey change:

  1. // See if the title has been modified.
  2. $article->isDirty('title');

You can also flag fields as being modified. This is handy when appending intoarray fields as this wouldn’t automatically mark the field as dirty, onlyexchanging completely would.:

  1. // Add a comment and mark the field as changed.
  2. $article->comments[] = $newComment;
  3. $article->setDirty('comments', true);

In addition you can also base your conditional code on the original fieldvalues by using the getOriginal() method. This method will either returnthe original value of the field if it has been modified or its actual value.

You can also check for changes to any field in the entity:

  1. // See if the entity has changed
  2. $article->isDirty();

To remove the dirty mark from fields in an entity, you can use the clean()method:

  1. $article->clean();

When creating a new entity, you can avoid the fields from being marked as dirtyby passing an extra option:

  1. $article = new Article(['title' => 'New Article'], ['markClean' => true]);

To get a list of all dirty fields of an Entity you may call:

  1. $dirtyFields = $entity->getDirty();

Validation Errors

After you save an entity any validation errors will bestored on the entity itself. You can access any validation errors using thegetErrors(), getError() or hasErrors() methods:

  1. // Get all the errors
  2. $errors = $user->getErrors();
  3.  
  4. // Get the errors for a single field.
  5. $errors = $user->getError('password');
  6.  
  7. // Does the entity or any nested entity have an error.
  8. $user->hasErrors();
  9.  
  10. // Does only the root entity have an error
  11. $user->hasErrors(false);

The setErrors() or setError() method can also be used to set the errorson an entity, making it easier to test code that works with error messages:

  1. $user->setError('password', ['Password is required']);
  2. $user->setErrors([
  3. 'password' => ['Password is required'],
  4. 'username' => ['Username is required']
  5. ]);

Mass Assignment

While setting fields to entities in bulk is simple and convenient, it cancreate significant security issues. Bulk assigning user data from the requestinto an entity allows the user to modify any and all columns. When usinganonymous entity classes or creating the entity class with the Bake ConsoleCakePHP does not protect against mass-assignment.

The _accessible property allows you to provide a map of fields andwhether or not they can be mass-assigned. The values true and falseindicate whether a field can or cannot be mass-assigned:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class Article extends Entity
  6. {
  7. protected $_accessible = [
  8. 'title' => true,
  9. 'body' => true
  10. ];
  11. }

In addition to concrete fields there is a special * field which defines thefallback behavior if a field is not specifically named:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class Article extends Entity
  6. {
  7. protected $_accessible = [
  8. 'title' => true,
  9. 'body' => true,
  10. '*' => false,
  11. ];
  12. }

Note

If the * field is not defined it will default to false.

Avoiding Mass Assignment Protection

When creating a new entity using the new keyword you can tell it to notprotect itself against mass assignment:

  1. use App\Model\Entity\Article;
  2.  
  3. $article = new Article(['id' => 1, 'title' => 'Foo'], ['guard' => false]);

Modifying the Guarded Fields at Runtime

You can modify the list of guarded fields at runtime using the setAccess()method:

  1. // Make user_id accessible.
  2. $article->setAccess('user_id', true);
  3.  
  4. // Make title guarded.
  5. $article->setAccess('title', false);

Note

Modifying accessible fields affects only the instance the method is calledon.

When using the newEntity() and patchEntity() methods in the Tableobjects you can customize mass assignment protection with options. Please referto the Changing Accessible Fields section for more information.

Bypassing Field Guarding

There are some situations when you want to allow mass-assignment to guardedfields:

  1. $article->set($fields, ['guard' => false]);

By setting the guard option to false, you can ignore the accessiblefield list for a single call to set().

Checking if an Entity was Persisted

It is often necessary to know if an entity represents a row that is alreadyin the database. In those situations use the isNew() method:

  1. if (!$article->isNew()) {
  2. echo 'This article was saved already!';
  3. }

If you are certain that an entity has already been persisted, you can useisNew() as a setter:

  1. $article->isNew(false);
  2.  
  3. $article->isNew(true);

Lazy Loading Associations

While eager loading associations is generally the most efficient way to accessyour associations, there may be times when you need to lazily load associateddata. Before we get into how to lazy load associations, we should discuss thedifferences between eager loading and lazy loading associations:

  • Eager loading
  • Eager loading uses joins (where possible) to fetch data from thedatabase in as few queries as possible. When a separate query is required,like in the case of a HasMany association, a single query is emitted tofetch all the associated data for the current set of objects.
  • Lazy loading
  • Lazy loading defers loading association data until it is absolutelyrequired. While this can save CPU time because possibly unused data is nothydrated into objects, it can result in many more queries being emitted tothe database. For example looping over a set of articles & their commentswill frequently emit N queries where N is the number of articles beingiterated.

While lazy loading is not included by CakePHP’s ORM, you can just use one of thecommunity plugins to do so. We recommend the LazyLoad Plugin

After adding the plugin to your entity, you will be able to do the following:

  1. $article = $this->Articles->findById($id);
  2.  
  3. // The comments property was lazy loaded
  4. foreach ($article->comments as $comment) {
  5. echo $comment->body;
  6. }

Creating Re-usable Code with Traits

You may find yourself needing the same logic in multiple entity classes. PHP’straits are a great fit for this. You can put your application’s traits insrc/Model/Entity. By convention traits in CakePHP are suffixed withTrait so they can be discernible from classes or interfaces. Traits areoften a good complement to behaviors, allowing you to provide functionality forthe table and entity objects.

For example if we had SoftDeletable plugin, it could provide a trait. This traitcould give methods for marking entities as ‘deleted’, the method softDeletecould be provided by a trait:

  1. // SoftDelete/Model/Entity/SoftDeleteTrait.php
  2.  
  3. namespace SoftDelete\Model\Entity;
  4.  
  5. trait SoftDeleteTrait
  6. {
  7. public function softDelete()
  8. {
  9. $this->set('deleted', true);
  10. }
  11. }

You could then use this trait in your entity class by importing it and includingit:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4. use SoftDelete\Model\Entity\SoftDeleteTrait;
  5.  
  6. class Article extends Entity
  7. {
  8. use SoftDeleteTrait;
  9. }

Converting to Arrays/JSON

When building APIs, you may often need to convert entities into arrays or JSONdata. CakePHP makes this simple:

  1. // Get an array.
  2. // Associations will be converted with toArray() as well.
  3. $array = $user->toArray();
  4.  
  5. // Convert to JSON
  6. // Associations will be converted with jsonSerialize hook as well.
  7. $json = json_encode($user);

When converting an entity to an JSON, the virtual & hidden field lists areapplied. Entities are recursively converted to JSON as well. This means that if youeager loaded entities and their associations CakePHP will correctly handleconverting the associated data into the correct format.

Exposing Virtual Fields

By default virtual fields are not exported when converting entities toarrays or JSON. In order to expose virtual fields you need to make themvisible. When defining your entity class you can provide a list of virtualfield that should be exposed:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class User extends Entity
  6. {
  7. protected $_virtual = ['full_name'];
  8. }

This list can be modified at runtime using the setVirtual() method:

  1. $user->setVirtual(['full_name', 'is_admin']);

Hiding Fields

There are often fields you do not want exported in JSON or array formats. Forexample it is often unwise to expose password hashes or account recoveryquestions. When defining an entity class, define which fields should behidden:

  1. namespace App\Model\Entity;
  2.  
  3. use Cake\ORM\Entity;
  4.  
  5. class User extends Entity
  6. {
  7. protected $_hidden = ['password'];
  8. }

This list can be modified at runtime using the setHidden() method:

  1. $user->setHidden(['password', 'recovery_question']);

Storing Complex Types

Accessor & Mutator methods on entities are not intended to contain the logic forserializing and unserializing complex data coming from the database. Refer tothe Saving Complex Types section to understand how your application canstore more complex data types like arrays and objects.