W3cubDocs

/CakePHP 4.1

Class Entity

An entity represents a single result row from a repository. It exposes the methods for retrieving and storing properties associated in this row.

Namespace: Cake\ORM

Properties summary

  • $_accessible protected
    bool[]

    Map of fields in this entity that can be safely assigned, each field name points to a boolean indicating its status. An empty array means no fields are accessible

  • $_accessors protected static
    array

    Holds a cached list of getters/setters per class

  • $_dirty protected
    bool[]

    Holds a list of the fields that were modified or added after this object was originally created.

  • $_errors protected
    array

    List of errors per field as stored in this object.

  • $_fields protected
    array

    Holds all fields and their values for this entity.

  • $_hidden protected
    string[]

    List of field names that should not be included in JSON or Array representations of this Entity.

  • $_invalid protected
    array

    List of invalid fields and their data for errors upon validation/patching.

  • $_new protected
    bool

    Indicates whether or not this entity is yet to be persisted.

  • $_original protected
    array

    Holds all fields that have been changed and their original values for this entity.

  • $_registryAlias protected
    string

    The alias of the repository this entity came from

  • $_virtual protected
    string[]

    List of computed or virtual fields that should be included in JSON or array representations of this Entity. If a field is present in both _hidden and _virtual the field will not be in the array/JSON versions of the entity.

  • $id public
    mixed

    Alias for commonly used primary key.

Method Summary

  • __construct() public

    Initializes the internal properties of this entity out of the keys in an array. The following list of options can be used:

  • __debugInfo() public

    Returns an array that can be used to describe the internal state of this object.

  • __get() public

    Magic getter to access fields that have been set in this entity

  • __isset() public

    Returns whether this entity contains a field named $field regardless of if it is empty.

  • __set() public

    Magic setter to add or edit a field in this entity

  • __toString() public

    Returns a string representation of this object in a human readable format.

  • __unset() public

    Removes a field from this entity

  • _accessor() protected static

    Fetch accessor method name Accessor methods (available or not) are cached in $_accessors

  • _nestedErrors() protected

    Auxiliary method for getting errors in nested entities

  • _readError() protected

    Read the error(s) from one or many objects.

  • _readHasErrors() protected

    Reads if there are errors for one or many objects.

  • clean() public

    Sets the entire entity as clean, which means that it will appear as no fields being modified or added at all. This is an useful call for an initial object hydration

  • extract() public

    Returns an array with the requested fields stored in this entity, indexed by field name

  • extractOriginal() public

    Returns an array with the requested original fields stored in this entity, indexed by field name.

  • extractOriginalChanged() public

    Returns an array with only the original fields stored in this entity, indexed by field name.

  • get() public

    Returns the value of a field by name

  • getAccessible() public

    Returns the raw accessible configuration for this entity.

  • getDirty() public

    Gets the dirty fields.

  • getError() public

    Returns validation errors of a field

  • getErrors() public

    Returns all validation errors.

  • getHidden() public

    Gets the hidden fields.

  • getInvalid() public

    Get a list of invalid fields and their data for errors upon validation/patching

  • getInvalidField() public

    Get a single value of an invalid field. Returns null if not set.

  • getOriginal() public

    Returns the value of an original field by name

  • getOriginalValues() public

    Gets all original values of the entity.

  • getSource() public

    Returns the alias of the repository from which this entity came from.

  • getVirtual() public

    Gets the virtual fields on this entity.

  • getVisible() public

    Gets the list of visible fields.

  • has() public

    Returns whether this entity contains a field named $field that contains a non-null value.

  • hasErrors() public

    Returns whether this entity has errors.

  • hasValue() public

    Checks tha a field has a value.

  • isAccessible() public

    Checks if a field is accessible

  • isDirty() public

    Checks if the entity is dirty or if a single field of it is dirty.

  • isEmpty() public

    Checks that a field is empty

  • isNew() public

    Returns whether or not this entity has already been persisted.

  • jsonSerialize() public

    Returns the fields that will be serialized as JSON

  • offsetExists() public

    Implements isset($entity);

  • offsetGet() public

    Implements $entity[$offset];

  • offsetSet() public

    Implements $entity[$offset] = $value;

  • offsetUnset() public

    Implements unset($result[$offset]);

  • set() public

    Sets a single field inside this entity.

  • setAccess() public

    Stores whether or not a field value can be changed or set in this entity.

  • setDirty() public

    Sets the dirty status of a single field.

  • setError() public

    Sets errors for a single field

  • setErrors() public

    Sets error messages to the entity

  • setHidden() public

    Sets hidden fields.

  • setInvalid() public

    Set fields as invalid and not patchable into the entity.

  • setInvalidField() public

    Sets a field as invalid and not patchable into the entity.

  • setNew() public

    Set the status of this entity.

  • setSource() public

    Sets the source alias

  • setVirtual() public

    Sets the virtual fields on this entity.

  • toArray() public

    Returns an array with all the fields that have been set to this entity

  • unset() public

    Removes a field or list of fields from this entity

  • unsetProperty() public

    Removes a field or list of fields from this entity

Method Detail

__construct() public

__construct(array $properties, array $options)

Initializes the internal properties of this entity out of the keys in an array. The following list of options can be used:

  • useSetters: whether use internal setters for properties or not
  • markClean: whether to mark all properties as clean after setting them
  • markNew: whether this instance has not yet been persisted
  • guard: whether to prevent inaccessible properties from being set (default: false)
  • source: A string representing the alias of the repository this entity came from

Example:

$entity = new Entity(['id' => 1, 'name' => 'Andrew'])

Parameters

array $properties optional

hash of properties to set in this entity

array $options optional

list of options to use when creating this entity

__debugInfo() public

__debugInfo()

Returns an array that can be used to describe the internal state of this object.

Returns

array

__get() public

__get(string $field)

Magic getter to access fields that have been set in this entity

Parameters

string $field

Name of the field to access

Returns

mixed

__isset() public

__isset(string $field)

Returns whether this entity contains a field named $field regardless of if it is empty.

Parameters

string $field

The field to check.

Returns

bool

See Also

\Cake\ORM\Entity::has()

__set() public

__set(string $field, mixed $value)

Magic setter to add or edit a field in this entity

Parameters

string $field

The name of the field to set

mixed $value

The value to set to the field

__toString() public

__toString()

Returns a string representation of this object in a human readable format.

Returns

string

__unset() public

__unset(string $field)

Removes a field from this entity

Parameters

string $field

The field to unset

_accessor() protected static

_accessor(string $property, string $type)

Fetch accessor method name Accessor methods (available or not) are cached in $_accessors

Parameters

string $property

the field name to derive getter name from

string $type

the accessor type ('get' or 'set')

Returns

string

method name or empty string (no method available)

_nestedErrors() protected

_nestedErrors(string $field)

Auxiliary method for getting errors in nested entities

Parameters

string $field

the field in this entity to check for errors

Returns

array

errors in nested entity if any

_readError() protected

_readError(mixed $object, mixed $path)

Read the error(s) from one or many objects.

Parameters

iterable|\Cake\Datasource\EntityInterface $object

The object to read errors from.

string|null $path optional

The field name for errors.

Returns

array

_readHasErrors() protected

_readHasErrors(mixed $object)

Reads if there are errors for one or many objects.

Parameters

array|\Cake\Datasource\EntityInterface $object

The object to read errors from.

Returns

bool

clean() public

clean()

Sets the entire entity as clean, which means that it will appear as no fields being modified or added at all. This is an useful call for an initial object hydration

extract() public

extract(array $fields, bool $onlyDirty)

Returns an array with the requested fields stored in this entity, indexed by field name

Parameters

string[] $fields

list of fields to be returned

bool $onlyDirty optional

Return the requested field only if it is dirty

Returns

array

extractOriginal() public

extractOriginal(array $fields)

Returns an array with the requested original fields stored in this entity, indexed by field name.

Fields that are unchanged from their original value will be included in the return of this method.

Parameters

string[] $fields

List of fields to be returned

Returns

array

extractOriginalChanged() public

extractOriginalChanged(array $fields)

Returns an array with only the original fields stored in this entity, indexed by field name.

This method will only return fields that have been modified since the entity was built. Unchanged fields will be omitted.

Parameters

string[] $fields

List of fields to be returned

Returns

array

get() public

get(string $field)

Returns the value of a field by name

Parameters

string $field

the name of the field to retrieve

Returns

mixed

Throws

InvalidArgumentException
if an empty field name is passed

getAccessible() public

getAccessible()

Returns the raw accessible configuration for this entity.

The * wildcard refers to all fields.

Returns

bool[]

getDirty() public

getDirty()

Gets the dirty fields.

Returns

string[]

getError() public

getError(string $field)

Returns validation errors of a field

Parameters

string $field

Field name to get the errors from

Returns

array

getErrors() public

getErrors()

Returns all validation errors.

Returns

array

getHidden() public

getHidden()

Gets the hidden fields.

Returns

string[]

getInvalid() public

getInvalid()

Get a list of invalid fields and their data for errors upon validation/patching

Returns

array

getInvalidField() public

getInvalidField(string $field)

Get a single value of an invalid field. Returns null if not set.

Parameters

string $field

The name of the field.

Returns

mixed|null

getOriginal() public

getOriginal(string $field)

Returns the value of an original field by name

Parameters

string $field

the name of the field for which original value is retrieved.

Returns

mixed

Throws

InvalidArgumentException
if an empty field name is passed.

getOriginalValues() public

getOriginalValues()

Gets all original values of the entity.

Returns

array

getSource() public

getSource()

Returns the alias of the repository from which this entity came from.

Returns

string

getVirtual() public

getVirtual()

Gets the virtual fields on this entity.

Returns

string[]

getVisible() public

getVisible()

Gets the list of visible fields.

The list of visible fields is all standard fields plus virtual fields minus hidden fields.

Returns

string[]

A list of fields that are 'visible' in all representations.

has() public

has(mixed $field)

Returns whether this entity contains a field named $field that contains a non-null value.

Example:

$entity = new Entity(['id' => 1, 'name' => null]);
$entity->has('id'); // true
$entity->has('name'); // false
$entity->has('last_name'); // false

You can check multiple fields by passing an array:

$entity->has(['name', 'last_name']);

All fields must not be null to get a truthy result.

When checking multiple fields. All fields must not be null in order for true to be returned.

Parameters

string|string[] $field

The field or fields to check.

Returns

bool

hasErrors() public

hasErrors(bool $includeNested)

Returns whether this entity has errors.

Parameters

bool $includeNested optional

true will check nested entities for hasErrors()

Returns

bool

hasValue() public

hasValue(string $field)

Checks tha a field has a value.

This method will return true for

  • Non-empty strings
  • Non-empty arrays
  • Any object
  • Integer, even 0
  • Float, even 0.0

and false in all other cases.

Parameters

string $field

The field to check.

Returns

bool

isAccessible() public

isAccessible(string $field)

Checks if a field is accessible

Example:

$entity->isAccessible('id'); // Returns whether it can be set or not

Parameters

string $field

Field name to check

Returns

bool

isDirty() public

isDirty(?string $field)

Checks if the entity is dirty or if a single field of it is dirty.

Parameters

string|null $field optional

The field to check the status for. Null for the whole entity.

Returns

bool

Whether the field was changed or not

isEmpty() public

isEmpty(string $field)

Checks that a field is empty

This is not working like the PHP empty() function. The method will return true for:

  • '' (empty string)
  • null
  • []

and false in all other cases.

Parameters

string $field

The field to check.

Returns

bool

isNew() public

isNew()

Returns whether or not this entity has already been persisted.

Returns

bool

Whether or not the entity has been persisted.

jsonSerialize() public

jsonSerialize()

Returns the fields that will be serialized as JSON

Returns

array

offsetExists() public

offsetExists(mixed $offset)

Implements isset($entity);

Parameters

string $offset

The offset to check.

Returns

bool

Success

offsetGet() public

offsetGet(mixed $offset)

Implements $entity[$offset];

Parameters

string $offset

The offset to get.

Returns

mixed

offsetSet() public

offsetSet(mixed $offset, mixed $value)

Implements $entity[$offset] = $value;

Parameters

string $offset

The offset to set.

mixed $value

The value to set.

offsetUnset() public

offsetUnset(mixed $offset)

Implements unset($result[$offset]);

Parameters

string $offset

The offset to remove.

set() public

set(mixed $field, mixed $value, array $options)

Sets a single field inside this entity.

Example:

$entity->set('name', 'Andrew');

It is also possible to mass-assign multiple fields to this entity with one call by passing a hashed array as fields in the form of field => value pairs

Example:

$entity->set(['name' => 'andrew', 'id' => 1]);
echo $entity->name // prints andrew
echo $entity->id // prints 1

Some times it is handy to bypass setter functions in this entity when assigning fields. You can achieve this by disabling the setter option using the $options parameter:

$entity->set('name', 'Andrew', ['setter' => false]);
$entity->set(['name' => 'Andrew', 'id' => 1], ['setter' => false]);

Mass assignment should be treated carefully when accepting user input, by default entities will guard all fields when fields are assigned in bulk. You can disable the guarding for a single set call with the guard option:

$entity->set(['name' => 'Andrew', 'id' => 1], ['guard' => false]);

You do not need to use the guard option when assigning fields individually:

// No need to use the guard option.
$entity->set('name', 'Andrew');

Parameters

string|array $field

the name of field to set or a list of fields with their respective values

mixed $value optional

The value to set to the field or an array if the first argument is also an array, in which case will be treated as $options

array $options optional

options to be used for setting the field. Allowed option keys are setter and guard

Returns

$this

Throws

InvalidArgumentException

setAccess() public

setAccess(mixed $field, bool $set)

Stores whether or not a field value can be changed or set in this entity.

The special field * can also be marked as accessible or protected, meaning that any other field specified before will take its value. For example $entity->setAccess('*', true) means that any field not specified already will be accessible by default.

You can also call this method with an array of fields, in which case they will each take the accessibility value specified in the second argument.

Example:

$entity->setAccess('id', true); // Mark id as not protected
$entity->setAccess('author_id', false); // Mark author_id as protected
$entity->setAccess(['id', 'user_id'], true); // Mark both fields as accessible
$entity->setAccess('*', false); // Mark all fields as protected

Parameters

string|array $field

Single or list of fields to change its accessibility

bool $set

True marks the field as accessible, false will mark it as protected.

Returns

$this

setDirty() public

setDirty(string $field, bool $isDirty)

Sets the dirty status of a single field.

Parameters

string $field

the field to set or check status for

bool $isDirty optional

true means the field was changed, false means it was not changed. Defaults to true.

Returns

$this

setError() public

setError(string $field, mixed $errors, bool $overwrite)

Sets errors for a single field

Example

// Sets the error messages for a single field
$entity->setError('salary', ['must be numeric', 'must be a positive number']);

Parameters

string $field

The field to get errors for, or the array of errors to set.

string|array $errors

The errors to be set for $field

bool $overwrite optional

Whether or not to overwrite pre-existing errors for $field

Returns

$this

setErrors() public

setErrors(array $errors, bool $overwrite)

Sets error messages to the entity

Example

// Sets the error messages for multiple fields at once
$entity->setErrors(['salary' => ['message'], 'name' => ['another message']]);

Parameters

array $errors

The array of errors to set.

bool $overwrite optional

Whether or not to overwrite pre-existing errors for $fields

Returns

$this

setHidden() public

setHidden(array $fields, bool $merge)

Sets hidden fields.

Parameters

string[] $fields

An array of fields to hide from array exports.

bool $merge optional

Merge the new fields with the existing. By default false.

Returns

$this

setInvalid() public

setInvalid(array $fields, bool $overwrite)

Set fields as invalid and not patchable into the entity.

This is useful for batch operations when one needs to get the original value for an error message after patching. This value could not be patched into the entity and is simply copied into the _invalid property for debugging purposes or to be able to log it away.

Parameters

array $fields

The values to set.

bool $overwrite optional

Whether or not to overwrite pre-existing values for $field.

Returns

$this

setInvalidField() public

setInvalidField(string $field, mixed $value)

Sets a field as invalid and not patchable into the entity.

Parameters

string $field

The value to set.

mixed $value

The invalid value to be set for $field.

Returns

$this

setNew() public

setNew(bool $new)

Set the status of this entity.

Using true means that the entity has not been persisted in the database, false that it already is.

Parameters

bool $new

Indicate whether or not this entity has been persisted.

Returns

$this

setSource() public

setSource(string $alias)

Sets the source alias

Parameters

string $alias

the alias of the repository

Returns

$this

setVirtual() public

setVirtual(array $fields, bool $merge)

Sets the virtual fields on this entity.

Parameters

string[] $fields

An array of fields to treat as virtual.

bool $merge optional

Merge the new fields with the existing. By default false.

Returns

$this

toArray() public

toArray()

Returns an array with all the fields that have been set to this entity

This method will recursively transform entities assigned to fields into arrays as well.

Returns

array

unset() public

unset(mixed $field)

Removes a field or list of fields from this entity

Examples:

$entity->unset('name');
$entity->unset(['name', 'last_name']);

Parameters

string|string[] $field

The field to unset.

Returns

$this

unsetProperty() public

unsetProperty(mixed $field)

Removes a field or list of fields from this entity

Parameters

string|string[] $field

The field to unset.

Returns

$this

Property Detail

$_accessible protected

Map of fields in this entity that can be safely assigned, each field name points to a boolean indicating its status. An empty array means no fields are accessible

The special field '*' can also be mapped, meaning that any other field not defined in the map will take its value. For example, '\*' => true means that any field not defined in the map will be accessible by default

Type

bool[]

$_accessors protected static

Holds a cached list of getters/setters per class

Type

array

$_dirty protected

Holds a list of the fields that were modified or added after this object was originally created.

Type

bool[]

$_errors protected

List of errors per field as stored in this object.

Type

array

$_fields protected

Holds all fields and their values for this entity.

Type

array

$_hidden protected

List of field names that should not be included in JSON or Array representations of this Entity.

Type

string[]

$_invalid protected

List of invalid fields and their data for errors upon validation/patching.

Type

array

$_new protected

Indicates whether or not this entity is yet to be persisted.

Entities default to assuming they are new. You can use Table::persisted() to set the new flag on an entity based on records in the database.

Type

bool

$_original protected

Holds all fields that have been changed and their original values for this entity.

Type

array

$_registryAlias protected

The alias of the repository this entity came from

Type

string

$_virtual protected

List of computed or virtual fields that should be included in JSON or array representations of this Entity. If a field is present in both _hidden and _virtual the field will not be in the array/JSON versions of the entity.

Type

string[]

$id public

Alias for commonly used primary key.

Type

mixed

© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.1/class-Cake.ORM.Entity.html