Please note that if you are using the Mongo driver provided by PHP 7, the ODM will not work for you. There is an incubator adapter but all the Mongo code must be rewritten (new Bson type instead of arrays, no MongoId, no MongoDate, etc...). Please ensure that you test your code before upgrading to PHP 7 and/or Phalcon 3+

ODM (Object-Document Mapper)

In addition to its ability to map tables in relational databases, Phalcon can map documents from NoSQL databases. The ODM offers a CRUD functionality, events, validations among other services.

Due to the absence of SQL queries and planners, NoSQL databases can see real improvements in performance using the Phalcon approach. Additionally, there are no SQL building reducing the possibility of SQL injections.

Setting a Connection

Connections are retrieved from the services container. By default, Phalcon tries to find the connection in a service called mongo:

<?php// Simple database connection to localhost$di->set('mongo',function(){$mongo=newMongoClient();return$mongo->selectDB('store');},true);// Connecting to a domain socket, falling back to localhost connection$di->set('mongo',function(){$mongo=newMongoClient('mongodb:///tmp/mongodb-27017.sock,localhost:27017');return$mongo->selectDB('store');},true);

Finding Documents

As Phalcon\Mvc\Collection relies on the Mongo PHP extension you have the same facilities to query documents and convert them transparently to model instances:

<?php// How many robots are there?$robots=Robots::find();echo'There are ',count($robots),"\n";// How many mechanical robots are there?$robots=Robots::find([['type'=>'mechanical',]]);echo'There are ',count($robots),"\n";// Get and print mechanical robots ordered by name upward$robots=Robots::find([['type'=>'mechanical',],'sort'=>['name'=>1,],]);foreach($robotsas$robot){echo$robot->name,"\n";}// Get first 100 mechanical robots ordered by name$robots=Robots::find([['type'=>'mechanical',],'sort'=>['name'=>1,],'limit'=>100,]);foreach($robotsas$robot){echo$robot->name,"\n";}

You could also use the findFirst() method to get only the first record matching the given criteria:

<?php// What's the first robot in robots collection?$robot=Robots::findFirst();echo'The robot name is ',$robot->name,"\n";// What's the first mechanical robot in robots collection?$robot=Robots::findFirst([['type'=>'mechanical',]]);echo'The first mechanical robot name is ',$robot->name,"\n";

Both find() and findFirst() methods accept an associative array specifying the search criteria:

<?php// First robot where type = 'mechanical' and year = '1999'$robot=Robots::findFirst(['conditions'=>['type'=>'mechanical','year'=>'1999',],]);// All virtual robots ordered by name downward$robots=Robots::find(['conditions'=>['type'=>'virtual',],'sort'=>['name'=>-1,],]);// Find all robots that have more than 4 friends using the where condition$robots=Robots::find(['conditions'=>['$where'=>'this.friends.length > 4',]]);

The available query options are:

Parameter

Description

Example

conditions

Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon_model assumes the first parameter are the conditions.

'conditions' => array('$gt' => 1990)

fields

Returns specific columns instead of the full fields in the collection. When using this option an incomplete object is returned

'fields' => array('name' => true)

sort

It’s used to sort the resultset. Use one or more fields as each element in the array, 1 means ordering upwards, -1 downward

Querying specific fields

To query specific fields specific fields from a MongoDB database using the Phalcon ODM, all you need to do is:

$myRobots=Robots:find(['fields'=>['name'=>1]]];

The find() above only returns a name. It can also be combined with a condition:

$myRobots=Robots:find([['type'=>'maid'],'fields'=>['name'=>1]]];

The example above returns the name of the robot with the type = 'maid'.

Aggregations

A model can return calculations using aggregation framework provided by Mongo. The aggregated values are calculate without having to use MapReduce. With this option is easy perform tasks such as totaling or averaging field values:

Creating Updating/Records

The Phalcon\Mvc\Collection::save() method allows you to create/update documents according to whether they already exist in the collection associated with a model. The save() method is called internally by the create and update methods of Phalcon\Mvc\Collection.

Also the method executes associated validators and events that are defined in the model:

<?php$robot=newRobots();$robot->type='mechanical';$robot->name='Astro Boy';$robot->year=1952;if($robot->save()===false){echo"Umh, We can't store robots right now: \n";$messages=$robot->getMessages();foreach($messagesas$message){echo$message,"\n";}}else{echo'Great, a new robot was saved successfully!';}

The _id property is automatically updated with the MongoId object created by the driver:

<?php$robot->save();echo'The generated id is: ',$robot->getId();

Validation Messages

Phalcon\Mvc\Collection has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes.

Each message consists of an instance of the class Phalcon\Mvc\Model\Message. The set of messages generated can be retrieved with the method getMessages(). Each message provides extended information like the field name that generated the message or the message type:

Validation Events and Events Manager

Models allow you to implement events that will be thrown when performing an insert or update. They help define business rules for a certain model. The following are the events supported by Phalcon\Mvc\Collection and their order of execution:

Operation

Name

Can stop operation?

Explanation

Inserting/Updating

beforeValidation

YES

Is executed before the validation process and the final insert/update to the database

Inserting

beforeValidationOnCreate

YES

Is executed before the validation process only when an insertion operation is being made

Updating

beforeValidationOnUpdate

YES

Is executed before the fields are validated for not nulls or foreign keys when an updating operation is being made

Inserting/Updating

onValidationFails

YES (already stopped)

Is executed before the validation process only when an insertion operation is being made

Inserting

afterValidationOnCreate

YES

Is executed after the validation process when an insertion operation is being made

Updating

afterValidationOnUpdate

YES

Is executed after the validation process when an updating operation is being made

Inserting/Updating

afterValidation

YES

Is executed after the validation process

Inserting/Updating

beforeSave

YES

Runs before the required operation over the database system

Updating

beforeUpdate

YES

Runs before the required operation over the database system only when an updating operation is being made

Inserting

beforeCreate

YES

Runs before the required operation over the database system only when an inserting operation is being made

Updating

afterUpdate

NO

Runs after the required operation over the database system only when an updating operation is being made

Inserting

afterCreate

NO

Runs after the required operation over the database system only when an inserting operation is being made

Inserting/Updating

afterSave

NO

Runs after the required operation over the database system

To make a model to react to an event, we must to implement a method with the same name of the event:

<?phpusePhalcon\Mvc\Collection;classRobotsextendsCollection{publicfunctionbeforeValidationOnCreate(){echo'This is executed before creating a Robot!';}}

Events can be useful to assign values before performing an operation, for example:

<?phpusePhalcon\Mvc\Collection;classProductsextendsCollection{publicfunctionbeforeCreate(){// Set the creation date$this->created_at=date('Y-m-d H:i:s');}publicfunctionbeforeUpdate(){// Set the modification date$this->modified_in=date('Y-m-d H:i:s');}}

In the example given above the EventsManager only acted as a bridge between an object and a listener (the anonymous function). If we want all objects created in our application use the same EventsManager, then we need to assign this to the Models Manager:

Implementing a Business Rule

When an insert, update or delete is executed, the model verifies if there are any methods with the names of the events listed in the table above.

We recommend that validation methods are declared protected to prevent that business logic implementation from being exposed publicly.

The following example implements an event that validates the year cannot be smaller than 0 on update or insert:

<?phpusePhalcon\Mvc\Collection;classRobotsextendsCollection{protectedfunctionbeforeSave(){if($this->year<0){echo'Year cannot be smaller than zero!';returnfalse;}}}

Some events return false as an indication to stop the current operation. If an event doesn’t return anything, Phalcon\Mvc\Collection will assume a true value.

Validating Data Integrity

Phalcon\Mvc\Collection provides several events to validate data and implement business rules. The special validation event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation.

The following example shows how to use it:

<?phpusePhalcon\Mvc\Collection;usePhalcon\Validation;usePhalcon\Validation\Validator\InclusionIn;usePhalcon\Validation\Validator\Numericality;classRobotsextendsCollection{publicfunctionvalidation(){$validation=newValidation();$validation->add('type',newInclusionIn(['message'=>'Type must be: mechanical or virtual','domain'=>['Mechanical','Virtual',],]));$validation->add('price',newNumericality(['message'=>'Price must be numeric']));return$this->validate($validation);}}

The example above performs a validation using the built-in validator InclusionIn. It checks that the value of the field type is in a domain list. If the value is not included in the list, then the validator will fail and return false.

Setting multiple databases

In Phalcon, all models can share the same database connection or specify a connection per model. Actually, when Phalcon\Mvc\Collection needs to connect to the database it requests the mongo service in the application’s services container. You can overwrite this service by setting it in the initialize() method:

<?php// This service returns a mongo database at 192.168.1.100$di->set('mongo1',function(){$mongo=newMongoClient('mongodb://scott:[email protected]');return$mongo->selectDB('management');},true);// This service returns a mongo database at localhost$di->set('mongo2',function(){$mongo=newMongoClient('mongodb://localhost');return$mongo->selectDB('invoicing');},true);

Then, in the initialize() method, we define the connection service for the model:

Injecting services into Models

You may be required to access the application services within a model, the following example explains how to do that:

<?phpusePhalcon\Mvc\Collection;classRobotsextendsCollection{publicfunctionnotSave(){// Obtain the flash service from the DI container$flash=$this->getDI()->getShared('flash');$messages=$this->getMessages();// Show validation messagesforeach($messagesas$message){$flash->error((string)$message);}}}

The notSave event is triggered whenever a creating or updating action fails. We’re flashing the validation messages obtaining the flash service from the DI container. By doing this, we don’t have to print messages after each saving.