PHP Class lithium\data\Model

Models are tasked with providing meaning to otherwise raw and unprocessed data (e.g. user profile). Models expose a consistent and unified API to interact with an underlying datasource (e.g. MongoDB, CouchDB, MySQL) for operations such as querying, saving, updating and deleting data from the persistent storage. Models allow you to interact with your data in two fundamentally different ways: querying, and data mutation (saving/updating/deleting). All query-related operations may be done through the static find() method, along with some additional utility methods provided for convenience. Classes extending this one should, conventionally, be named as Singular, CamelCase and be placed in the app/models directory. i.e. a posts model would be app/model/Post.php. Examples: {{{ Return all 'post' records Post::find('all'); Post::all(); With conditions and a limit Post::find('all', array('conditions' => array('published' => true), 'limit' => 10)); Post::all(array('conditions' => array('published' => true), 'limit' => 10)); Integer count of all 'post' records Post::find('count'); Post::count(); // This is equivalent to the above. With conditions Post::find('count', array('conditions' => array('published' => true))); Post::count(array('published' => true)); }}} The actual objects returned from find() calls will depend on the type of datasource in use. MongoDB, for example, will return results as a Document, while MySQL will return results as a RecordSet. Both of these classes extend a common data\Collection class, and provide the necessary abstraction to make working with either type completely transparent. For data mutation (saving/updating/deleting), the Model class acts as a broker to the proper objects. When creating a new record, for example, a call to Post::create() will return a data\model\Record object, which can then be acted upon. Example: {{{ $post = Post::create(); $post->author = 'Robert'; $post->title = 'Newest Post!'; $post->content = 'Lithium rocks. That is all.'; $post->save(); }}}
See also: lithium\data\entity\Record
See also: lithium\data\entity\Document
See also: lithium\data\collection\RecordSet
See also: lithium\data\collection\DocumentSet
See also: lithium\data\Connections
Inheritance: extends lithium\core\StaticObject
Show file Open project: unionofrad/lithium Class Usage Examples

Public Properties

Property Type Description
$belongsTo array Model belongsTo relations.
$hasMany array Model hasMany relations.
$hasOne array Model hasOne relations.
$validates array Example usage: public $validates = array( 'title' => 'please enter a title', 'email' => array( array('notEmpty', 'message' => 'Email is empty.'), array('email', 'message' => 'Email is not valid.'), ) );

Protected Properties

Property Type Description
$_autoConfig array Holds an array of values that should be processed on Model::config(). Each value should have a matching protected property (prefixed with _) defined in the class. If the property is an array, the property name should be the key and the value should be 'merge'.
$_classes array Class dependencies.
$_finders array Custom find query properties, indexed by name.
$_inherits array Holds an array of attributes to be inherited.
$_initialized array List of initialized instances.
$_initializers array Array of closures used to lazily initialize metadata.
$_instanceFilters array Stores the filters that are applied to the model instances stored in Model::$_instances.
$_instanceMethods array Stores all custom instance methods created by Model::instanceMethods.
$_instances array While the Model public API does not require instantiation thanks to late static binding introduced in PHP 5.3, LSB does not apply to class attributes. In order to prevent you from needing to redeclare every single Model class attribute in subclasses, instances of the models are stored and used internally.
$_meta array - connection: The name of the connection (as defined in Connections::add()) to which the model should bind - key: The primary key or identifier key for records / documents this model produces, i.e. 'id' or array('_id', '_rev'). Defaults to 'id'. - name: The canonical name of this model. Defaults to the class name. - source: The name of the database table or document collection to bind to. Defaults to the lower-cased and underscored name of the class, i.e. class UserProfile maps to 'user_profiles'. - title: The field or key used as the title for each record. Defaults to 'title' or 'name', if those fields are available.
$_query array - 'conditions': The conditional query elements, e.g. array('published' => true). - 'fields': The fields that should be retrieved. When unset or explitily set to null, '*' or left unset, defaults to all fields. - 'order': The order in which the data will be returned, e.g. array('id' => 'ASC') or array('modified' => 'DESC'). - 'limit': The maximum number of records to return. - 'page': For pagination of data (equals limit * offset). - 'with': An array of relationship names to be included in the query.
$_relationFieldNames array Matching between relation's fieldnames and their corresponding relation name.
$_relationTypes array Valid relation types are: - belongsTo - hasOne - hasMany
$_relations array A list of the current relation types for this Model.
$_relationsToLoad Store available relation names for this model which still unloaded.
$_schema array The schema is lazy-loaded by the first call to Model::schema(), unless it has been manually defined in the Model subclass. For schemaless persistent storage (e.g. MongoDB), this is never populated automatically - if you desire a fixed schema to interact with in those cases, you will be required to define it yourself. Example: protected $_schema = array( '_id' => array('type' => 'id'), // required for Mongo 'name' => array('type' => 'string', 'default' => 'Moe', 'null' => false), 'sign' => array('type' => 'string', 'default' => 'bar', 'null' => false), 'age' => array('type' => 'integer', 'default' => 0, 'null' => false) ); For MongoDB specifically, you can also implement a callback in your database connection configuration that fetches and returns the schema data, as in the following: config/bootstrap/connections.php: Connections::add('default', array( 'type' => 'MongoDb', 'host' => 'localhost', 'database' => 'app_name', 'schema' => function($db, $collection, $meta) { $result = $db->connection->schemas->findOne(compact('collection')); return $result ? $result['data'] : array(); } )); This example defines an optional MongoDB convention in which the schema for each individual collection is stored in a "schemas" collection, where each document contains the name of a collection, along with a 'data' key, which contains the schema for that collection, in the format specified above. When defining '$_schema' where the data source is MongoDB, the types map to database types as follows: id => MongoId date => MongoDate regex => MongoRegex integer => integer float => float boolean => boolean code => MongoCode binary => MongoBinData

Public Methods

Method Description
__call ( string $method, array $params ) : mixed Magic method that allows calling Model::_instanceMethods's closure like normal methods on the model instance.
__callStatic ( string $method, array $params ) : mixed Enables magic finders. These provide some syntactic-sugar which allows to i.e. use Model::all() instead of Model::find('all').
applyFilter ( string $method, mixed $closure = null ) Wraps StaticObject::applyFilter() to account for object instances.
bind ( string $type, string $name, array $config = [] ) : object Creates a relationship binding between this model and another.
config ( array $config = [] ) Configures the model for use. This method will set the Model::$_schema, Model::$_meta, Model::$_finders class attributes, as well as obtain a handle to the configured persistent storage connection.
connection ( ) : object Gets the connection object to which this model is bound. Throws exceptions if a connection isn't set, or if the connection named isn't configured.
create ( array $data = [], array $options = [] ) : object Instantiates a new record or document object, initialized with any data passed in. For example:
delete ( object $entity, array $options = [] ) : boolean Deletes the data associated with the current Model.
find ( string | object | integer $type, array $options = [] ) : mixed The find method allows you to retrieve data from the connected data source.
finder ( string $name, string | callable | null $finder = null ) : callable | void Sets or gets a custom finder by name. The finder definition can be an array of default query options, or an anonymous functions that accepts an array of query options, and a function to continue. To get a finder specify just the name.
hasField ( mixed $field ) : mixed Checks to see if a particular field exists in a model's schema. Can check a single field, or return the first field found in an array of multiple options.
instanceMethods ( array $methods = null ) : array Getter and setter for custom instance methods. This is used in Entity::__call().
key ( mixed $values = null ) : mixed If no values supplied, returns the name of the Model key. If values are supplied, returns the key value.
meta ( string $key = null, string $value = null ) : mixed Gets or sets Model's metadata.
query ( array $query = null ) : mixed Gets or sets the default query for the model.
relations ( string $type = null ) : array | object | void Returns a list of models related to Model, or a list of models related to this model, but of a certain type.
remove ( mixed $conditions = [], array $options = [] ) : boolean Remove multiple documents or records based on a given set of criteria. **WARNING**: If no criteria are specified, or if the criteria ($conditions) is an empty value (i.e. an empty array or null), all the data in the backend data source (i.e. table or collection) _will_ be deleted.
reset ( ) Resetting the model.
respondsTo ( string $method, boolean $internal = false ) : boolean Determines if a given method can be called.
save ( object $entity, array $data = null, array $options = [] ) : boolean An instance method (called on record and document objects) to create or update the record or document in the database that corresponds to $entity.
schema ( mixed $field = null ) : array | lithium\data\Schema Lazy-initialize the schema for this Model object, if it is not already manually set in the object. You can declare `protected $_schema = array(.
title ( object $entity ) : string The title() method is invoked whenever an Entity object is cast or coerced to a string. This method can also be called on the entity directly, i.e. $post->title().
update ( mixed $data, mixed $conditions = [], array $options = [] ) : boolean Update multiple records or documents with the given data, restricted by the given set of criteria (optional).
validates ( object $entity, array $options = [] ) : boolean An important part of describing the business logic of a model class is defining the validation rules. In Lithium models, rules are defined through the $validates class property, and are used by this method before saving to verify the correctness of the data being sent to the backend data source.

Protected Methods

Method Description
_filter ( string $method, array $params, mixed $callback, array $filters = [] ) : object Wraps StaticObject::_filter() to account for object instances.
_finders ( ) : array Returns an array with the default finders.
_getMetaKey ( string $key = null ) : mixed Helper method used by meta() to generate and cache metadata values.
_inherit ( ) Merge parent class attributes to the current instance.
_inherited ( ) Return inherited attributes.
_initialize ( string $class ) : object Init default connection options and connects default finders.
_instance ( string | object $name, array $options = [] ) : object Returns an instance of a class with given config. The name could be a key from the classes array, a fully-namespaced class name, or an object. Typically this method is used in _init to create the dependencies used in the current class.
_key ( string $key, object $values, string $entity ) : mixed Helper for the Model::key() function
_object ( )
_relationFieldName ( $type, $name )
_relations ( $type = null, $name = null ) : An This method automagically bind in the fly unloaded relations.
_relationsToLoad ( ) : void Iterates through relationship types to construct relation map.

Method Details

__call() public method

Magic method that allows calling Model::_instanceMethods's closure like normal methods on the model instance.
See also: lithium\data\Model::instanceMethods
public __call ( string $method, array $params ) : mixed
$method string Method name caught by `__call()`.
$params array Arguments given to the above `$method` call.
return mixed

__callStatic() public static method

Retrieves post with id 23 using the 'first' finder. Posts::first(array('conditions' => array('id' => 23))); Posts::findById(23); Posts::findById(23); All posts that have a trueish is_published field. Posts::all(array('conditions' => array('is_published' => true))); Posts::findAll(array('conditions' => array('is_published' => true))); Posts::findAllByIsPublshed(true) Counts all posts. Posts::count()
See also: lithium\data\Model::find()
See also: lithium\data\Model::$_meta
public static __callStatic ( string $method, array $params ) : mixed
$method string Method name caught by `__callStatic()`.
$params array Arguments given to the above `$method` call.
return mixed Results of dispatched `Model::find()` call.

_filter() protected static method

Wraps StaticObject::_filter() to account for object instances.
See also: lithium\core\StaticObject::_filter()
protected static _filter ( string $method, array $params, mixed $callback, array $filters = [] ) : object
$method string
$params array
$callback mixed
$filters array Defaults to empty array.
return object

_finders() protected static method

Returns an array with the default finders.
See also: lithium\data\Model::_initialize()
protected static _finders ( ) : array
return array

_getMetaKey() protected method

Helper method used by meta() to generate and cache metadata values.
protected _getMetaKey ( string $key = null ) : mixed
$key string The name of the meta value to return, or `null`, to return all values.
return mixed Returns the value of the meta key specified by `$key`, or an array of all meta values if `$key` is `null`.

_inherit() protected method

Merge parent class attributes to the current instance.
protected _inherit ( )

_inherited() protected method

Return inherited attributes.
protected _inherited ( )

_initialize() protected static method

This method will set the Model::$_schema, Model::$_meta, Model::$_finders class attributes, as well as obtain a handle to the configured persistent storage connection
protected static _initialize ( string $class ) : object
$class string The fully-namespaced class name to initialize.
return object Returns the initialized model instance.

_instance() protected static method

Returns an instance of a class with given config. The name could be a key from the classes array, a fully-namespaced class name, or an object. Typically this method is used in _init to create the dependencies used in the current class.
protected static _instance ( string | object $name, array $options = [] ) : object
$name string | object A `classes` alias or fully-namespaced class name.
$options array The configuration passed to the constructor.
return object

_key() protected static method

Helper for the Model::key() function
See also: lithium\data\Model::key()
protected static _key ( string $key, object $values, string $entity ) : mixed
$key string The key
$values object Object with attributes.
$entity string The fully-namespaced entity class name.
return mixed The key value array or `null` if the `$values` object has no attribute named `$key`

_object() protected static method

protected static _object ( )

_relationFieldName() protected method

protected _relationFieldName ( $type, $name )

_relations() protected static method

This method automagically bind in the fly unloaded relations.
See also: lithium\data\Model::relations()
protected static _relations ( $type = null, $name = null ) : An
$type A type of model relation.
$name A relation name.
return An array of relation instances or an instance of relation.

_relationsToLoad() protected static method

Iterates through relationship types to construct relation map.
protected static _relationsToLoad ( ) : void
return void

applyFilter() public static method

Wraps StaticObject::applyFilter() to account for object instances.
See also: lithium\core\StaticObject::applyFilter()
public static applyFilter ( string $method, mixed $closure = null )
$method string
$closure mixed

bind() public static method

Creates a relationship binding between this model and another.
See also: lithium\data\model\Relationship
public static bind ( string $type, string $name, array $config = [] ) : object
$type string The type of relationship to create. Must be one of `'hasOne'`, `'hasMany'` or `'belongsTo'`.
$name string The name of the relationship. If this is also the name of the model, the model must be in the same namespace as this model. Otherwise, the fully-namespaced path to the model class must be specified in `$config`.
$config array Any other configuration that should be specified in the relationship. See the `Relationship` class for more information.
return object Returns an instance of the `Relationship` class that defines the connection.

config() public static method

Configures the model for use. This method will set the Model::$_schema, Model::$_meta, Model::$_finders class attributes, as well as obtain a handle to the configured persistent storage connection.
public static config ( array $config = [] )
$config array Possible options are: - `meta`: Meta-information for this model, such as the connection. - `finders`: Custom finders for this model. - `query`: Default query parameters. - `schema`: A `Schema` instance for this model. - `classes`: Classes used by this model.

connection() public static method

Gets the connection object to which this model is bound. Throws exceptions if a connection isn't set, or if the connection named isn't configured.
public static connection ( ) : object
return object Returns an instance of `lithium\data\Source` from the connection configuration to which this model is bound.

create() public static method

$post = Posts::create(array('title' => 'New post')); echo $post->title; // echoes 'New post' $success = $post->save(); Note that while this method creates a new object, there is no effect on the database until the save() method is called. In addition, this method can be used to simulate loading a pre-existing object from the database, without actually querying the database: $post = Posts::create(array('id' => $id, 'moreData' => 'foo'), array('exists' => true)); $post->title = 'New title'; $success = $post->save(); This will create an update query against the object with an ID matching $id. Also note that only the title field will be updated.
public static create ( array $data = [], array $options = [] ) : object
$data array Any data that this object should be populated with initially.
$options array Options to be passed to item.
return object Returns a new, _un-saved_ record or document object. In addition to the values passed to `$data`, the object will also contain any values assigned to the `'default'` key of each field defined in `$_schema`.

delete() public method

Deletes the data associated with the current Model.
public delete ( object $entity, array $options = [] ) : boolean
$entity object Entity to delete.
$options array Options.
return boolean Success.

find() public static method

Examples: Posts::find('all'); // returns all records Posts::find('count'); // returns a count of all records The first ten records that have 'author' set to 'Bob'. Posts::find('all', array( 'conditions' => array('author' => 'Bob'), 'limit' => 10 )); First record where the id matches 23. Posts::find('first', array( 'conditions' => array('id' => 23) )); Shorthands: Shorthand for find first by primary key. Posts::find(23); Also works with objects. Posts::find(new MongoId(23));
See also: lithium\data\Model::finder()
public static find ( string | object | integer $type, array $options = [] ) : mixed
$type string | object | integer The name of the finder to use. By default the following finders are available. Custom finders can be added via `Model::finder()`. - `'all'`: Returns all records matching the conditions. - `'first'`: Returns the first record matching the conditions. - `'count'`: Returns an integer count of all records matching the conditions. - `'list'`: Returns a one dimensional array, where the key is the (primary) key and the value the title of the record (the record must have a `'title'` field). A result may look like: `array(1 => 'Foo', 2 => 'Bar')`. Instead of the name of a finder, also supports shorthand usage with an object or integer as the first parameter. When passed such a value it is equal to `Model::find('first', array('conditions' => array('' => )))`. Note: When an undefined finder is tried to be used, the method will not error out, but fallback to the `'all'` finder.
$options array Options for the query. By default, accepts: - `'conditions'` _array_: The conditions for the query i.e. `'array('is_published' => true)`. - `'fields'` _array|null_: The fields that should be retrieved. When set to `null` and by default, uses all fields. To optimize query performance, limit the fields to just the ones actually needed. - `'order'` _array|string_: The order in which the data will be returned, i.e. `'created ASC'` sorts by created date in ascending order. To sort by multiple fields use the array syntax `array('title' => 'ASC', 'id' => 'ASC)`. - `'limit'` _integer_: The maximum number of records to return. - `'page'` _integer_: Allows to paginate data sets. Specifies the page of the set together with the limit option specifying the number of records per page. The first page starts at `1`.
return mixed The result/s of the find. Actual result depends on the finder being used. Most often this is an instance of `lithium\data\Collection` or `lithium\data\Entity`.

finder() public static method

In this example we define and use 'published' finder to quickly retrieve all published posts. Posts::finder('published', array( 'conditions' => array('is_published' => true) )); Posts::find('published'); Here we define the same finder using an anonymous function which gives us more control over query modification. Posts::finder('published', function($params, $next) { $params['options']['conditions']['is_published'] = true; Perform modifications before executing the query... $result = $next($params); ... or after it has executed. return $result; }); When using finder array definitions the option array is _recursivly_ merged (using Set::merge()) with additional options specified on the Model::find() call. Options specificed on the find will overwrite options specified in the finder. Array finder definitions are normalized here, so that it can be relied upon that defined finders are always anonymous functions.
See also: lithium\util\Set::merge()
public static finder ( string $name, string | callable | null $finder = null ) : callable | void
$name string The finder name, e.g. `'first'`.
$finder string | callable | null The finder definition.
return callable | void Returns finder definition if querying, or void if setting.

hasField() public static method

Checks to see if a particular field exists in a model's schema. Can check a single field, or return the first field found in an array of multiple options.
public static hasField ( mixed $field ) : mixed
$field mixed A single field (string) or list of fields (array) to check the existence of.
return mixed If `$field` is a string, returns a boolean indicating whether or not that field exists. If `$field` is an array, returns the first field found, or `false` if none of the fields in the list are found.

instanceMethods() public static method

Model::instanceMethods(array( 'methodName' => array('Class', 'method'), 'anotherMethod' => array($object, 'method'), 'closureCallback' => function($entity) } ));
See also: lithium\data\Entity::__call()
public static instanceMethods ( array $methods = null ) : array
$methods array
return array

key() public static method

If no values supplied, returns the name of the Model key. If values are supplied, returns the key value.
public static key ( mixed $values = null ) : mixed
$values mixed An array of values or object with values. If `$values` is `null`, the meta `'key'` of the model is returned.
return mixed Key value.

meta() public static method

Gets or sets Model's metadata.
See also: lithium\data\Model::$_meta
public static meta ( string $key = null, string $value = null ) : mixed
$key string Model metadata key.
$value string Model metadata value.
return mixed Metadata value for a given key.

query() public static method

Gets or sets the default query for the model.
public static query ( array $query = null ) : mixed
$query array Possible options are: - `'conditions'`: The conditional query elements, e.g. `'conditions' => array('published' => true)` - `'fields'`: The fields that should be retrieved. When set to `null`, defaults to all fields. - `'order'`: The order in which the data will be returned, e.g. `'order' => 'ASC'`. - `'limit'`: The maximum number of records to return. - `'page'`: For pagination of data. - `'with'`: An array of relationship names to be included in the query.
return mixed Returns the query definition if querying, or `null` if setting.

relations() public static method

Returns a list of models related to Model, or a list of models related to this model, but of a certain type.
public static relations ( string $type = null ) : array | object | void
$type string A type of model relation.
return array | object | void An array of relation instances or an instance of relation.

remove() public static method

Remove multiple documents or records based on a given set of criteria. **WARNING**: If no criteria are specified, or if the criteria ($conditions) is an empty value (i.e. an empty array or null), all the data in the backend data source (i.e. table or collection) _will_ be deleted.
public static remove ( mixed $conditions = [], array $options = [] ) : boolean
$conditions mixed An array of key/value pairs representing the scope of the records or documents to be deleted.
$options array Any database-specific options to use when performing the operation. See the `delete()` method of the corresponding backend database for available options.
return boolean Returns `true` if the remove operation succeeded, otherwise `false`.

reset() public static method

Resetting the model.
public static reset ( )

respondsTo() public static method

Determines if a given method can be called.
public static respondsTo ( string $method, boolean $internal = false ) : boolean
$method string Name of the method.
$internal boolean Provide `true` to perform check from inside the class/object. When `false` checks also for public visibility; defaults to `false`.
return boolean Returns `true` if the method can be called, `false` otherwise.

save() public method

For example, to create a new record or document: $post = Posts::create(); // Creates a new object, which doesn't exist in the database yet $post->title = "My post"; $success = $post->save(); It is also used to update existing database objects, as in the following: $post = Posts::first($id); $post->title = "Revised title"; $success = $post->save(); By default, an object's data will be checked against the validation rules of the model it is bound to. Any validation errors that result can then be accessed through the errors() method. if (!$post->save($someData)) { return array('errors' => $post->errors()); } To override the validation checks and save anyway, you can pass the 'validate' option: $post->title = "We Don't Need No Stinkin' Validation"; $post->body = "I know what I'm doing."; $post->save(null, array('validate' => false)); By default only validates and saves fields from the schema (if available). This behavior can be controlled via the 'whitelist' and 'locked' options.
See also: lithium\data\Model::$validates
See also: lithium\data\Model::validates()
See also: lithium\data\Entity::errors()
public save ( object $entity, array $data = null, array $options = [] ) : boolean
$entity object The record or document object to be saved in the database. This parameter is implicit and should not be passed under normal circumstances. In the above example, the call to `save()` on the `$post` object is transparently proxied through to the `Posts` model class, and `$post` is passed in as the `$entity` parameter.
$data array Any data that should be assigned to the record before it is saved.
$options array Options: - `'callbacks'` _boolean_: If `false`, all callbacks will be disabled before executing. Defaults to `true`. - `'validate'` _boolean|array_: If `false`, validation will be skipped, and the record will be immediately saved. Defaults to `true`. May also be specified as an array, in which case it will replace the default validation rules specified in the `$validates` property of the model. - `'events'` _string|array_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. They will be passed to the validates() method if `'validate'` is not `false`. - `'whitelist'` _array_: An array of fields that are allowed to be saved to this record. When unprovided will - if available - default to fields of the current schema and the `'locked'` option is not `false`. - `'locked'` _boolean_: Whether to use schema for saving just fields from the schema or not. Defaults to `true`.
return boolean Returns `true` on a successful save operation, `false` on failure.

schema() public static method

..)` to define the schema manually.
public static schema ( mixed $field = null ) : array | lithium\data\Schema
$field mixed Optional. You may pass a field name to get schema information for just one field. Otherwise, an array containing all fields is returned. If `false`, the schema is reset to an empty value. If an array, field definitions contained are appended to the schema.
return array | lithium\data\Schema

title() public method

By default, when generating the title for an object, it uses the the field specified in the 'title' key of the model's meta data definition. Override this method to generate custom titles for objects of this model's type.
See also: lithium\data\Model::$_meta
See also: lithium\data\Entity::__toString()
public title ( object $entity ) : string
$entity object The `Entity` instance on which the title method is called.
return string Returns the title representation of the entity on which this method is called.

update() public static method

Update multiple records or documents with the given data, restricted by the given set of criteria (optional).
public static update ( mixed $data, mixed $conditions = [], array $options = [] ) : boolean
$data mixed Typically an array of key/value pairs that specify the new data with which the records will be updated. For SQL databases, this can optionally be an SQL fragment representing the `SET` clause of an `UPDATE` query.
$conditions mixed An array of key/value pairs representing the scope of the records to be updated.
$options array Any database-specific options to use when performing the operation. See the `delete()` method of the corresponding backend database for available options.
return boolean Returns `true` if the update operation succeeded, otherwise `false`.

validates() public method

Note that these are application-level validation rules, and do not interact with any rules or constraints defined in your data source. If such constraints fail, an exception will be thrown by the database layer. The validates() method only checks against the rules defined in application code. This method uses the Validator class to perform data validation. An array representation of the entity object to be tested is passed to the check() method, along with the model's validation rules. Any rules defined in the Validator class can be used to validate fields. See the Validator class to add custom rules, or override built-in rules.
See also: lithium\data\Model::$validates
See also: lithium\util\Validator::check()
See also: lithium\data\Entity::errors()
public validates ( object $entity, array $options = [] ) : boolean
$entity object Model entity to validate. Typically either a `Record` or `Document` object. In the following example: ``` $post = Posts::create($data); $success = $post->validates(); ``` The `$entity` parameter is equal to the `$post` object instance.
$options array Available options: - `'rules'` _array_: If specified, this array will _replace_ the default validation rules defined in `$validates`. - `'events'` _mixed_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. For example, by default, `'events'` is set to either `'create'` or `'update'`, depending on whether `$entity` already exists. Then, individual rules can specify `'on' => 'create'` or `'on' => 'update'` to only be applied at certain times. Using this parameter, you can set up custom events in your rules as well, such as `'on' => 'login'`. Note that when defining validation rules, the `'on'` key can also be an array of multiple events. - `'required`' _mixed_: Represents whether the value is required to be present in `$values`. If `'required'` is set to `true`, the validation rule will be checked. if `'required'` is set to 'false' , the validation rule will be skipped if the corresponding key is not present. If don't set `'required'` or set this to `null`, the validation rule will be skipped if the corresponding key is not present in update and will be checked in insert. Defaults is set to `null`. - `'whitelist'` _array_: If specified, only fields in this array will be validated and others will be skipped.
return boolean Returns `true` if all validation rules on all fields succeed, otherwise `false`. After validation, the messages for any validation failures are assigned to the entity, and accessible through the `errors()` method of the entity object.

Property Details

$_autoConfig protected property

Holds an array of values that should be processed on Model::config(). Each value should have a matching protected property (prefixed with _) defined in the class. If the property is an array, the property name should be the key and the value should be 'merge'.
See also: lithium\data\Model::config()
protected array $_autoConfig
return array

$_classes protected property

Class dependencies.
protected array $_classes
return array

$_finders protected property

Custom find query properties, indexed by name.
See also: lithium\data\Model::finder()
protected array $_finders
return array

$_inherits protected property

Holds an array of attributes to be inherited.
See also: lithium\data\Model::_inherited()
protected array $_inherits
return array

$_initialized protected static property

List of initialized instances.
protected static array $_initialized
return array

$_initializers protected property

Array of closures used to lazily initialize metadata.
protected array $_initializers
return array

$_instanceFilters protected property

Stores the filters that are applied to the model instances stored in Model::$_instances.
protected array $_instanceFilters
return array

$_instanceMethods protected static property

Stores all custom instance methods created by Model::instanceMethods.
protected static array $_instanceMethods
return array

$_instances protected static property

While the Model public API does not require instantiation thanks to late static binding introduced in PHP 5.3, LSB does not apply to class attributes. In order to prevent you from needing to redeclare every single Model class attribute in subclasses, instances of the models are stored and used internally.
protected static array $_instances
return array

$_meta protected property

- connection: The name of the connection (as defined in Connections::add()) to which the model should bind - key: The primary key or identifier key for records / documents this model produces, i.e. 'id' or array('_id', '_rev'). Defaults to 'id'. - name: The canonical name of this model. Defaults to the class name. - source: The name of the database table or document collection to bind to. Defaults to the lower-cased and underscored name of the class, i.e. class UserProfile maps to 'user_profiles'. - title: The field or key used as the title for each record. Defaults to 'title' or 'name', if those fields are available.
See also: lithium\data\Connections::add()
protected array $_meta
return array

$_query protected property

- 'conditions': The conditional query elements, e.g. array('published' => true). - 'fields': The fields that should be retrieved. When unset or explitily set to null, '*' or left unset, defaults to all fields. - 'order': The order in which the data will be returned, e.g. array('id' => 'ASC') or array('modified' => 'DESC'). - 'limit': The maximum number of records to return. - 'page': For pagination of data (equals limit * offset). - 'with': An array of relationship names to be included in the query.
protected array $_query
return array

$_relationFieldNames protected property

Matching between relation's fieldnames and their corresponding relation name.
protected array $_relationFieldNames
return array

$_relationTypes protected property

Valid relation types are: - belongsTo - hasOne - hasMany
protected array $_relationTypes
return array

$_relations protected property

A list of the current relation types for this Model.
protected array $_relations
return array

$_relationsToLoad protected property

Store available relation names for this model which still unloaded.
protected $_relationsToLoad

$_schema protected property

The schema is lazy-loaded by the first call to Model::schema(), unless it has been manually defined in the Model subclass. For schemaless persistent storage (e.g. MongoDB), this is never populated automatically - if you desire a fixed schema to interact with in those cases, you will be required to define it yourself. Example: protected $_schema = array( '_id' => array('type' => 'id'), // required for Mongo 'name' => array('type' => 'string', 'default' => 'Moe', 'null' => false), 'sign' => array('type' => 'string', 'default' => 'bar', 'null' => false), 'age' => array('type' => 'integer', 'default' => 0, 'null' => false) ); For MongoDB specifically, you can also implement a callback in your database connection configuration that fetches and returns the schema data, as in the following: config/bootstrap/connections.php: Connections::add('default', array( 'type' => 'MongoDb', 'host' => 'localhost', 'database' => 'app_name', 'schema' => function($db, $collection, $meta) { $result = $db->connection->schemas->findOne(compact('collection')); return $result ? $result['data'] : array(); } )); This example defines an optional MongoDB convention in which the schema for each individual collection is stored in a "schemas" collection, where each document contains the name of a collection, along with a 'data' key, which contains the schema for that collection, in the format specified above. When defining '$_schema' where the data source is MongoDB, the types map to database types as follows: id => MongoId date => MongoDate regex => MongoRegex integer => integer float => float boolean => boolean code => MongoCode binary => MongoBinData
See also: lithium\data\source\MongoDb::$_schema
protected array $_schema
return array

$belongsTo public property

Model belongsTo relations.
public array $belongsTo
return array

$hasMany public property

Model hasMany relations.
public array $hasMany
return array

$hasOne public property

Model hasOne relations.
public array $hasOne
return array

$validates public property

Example usage: public $validates = array( 'title' => 'please enter a title', 'email' => array( array('notEmpty', 'message' => 'Email is empty.'), array('email', 'message' => 'Email is not valid.'), ) );
public array $validates
return array