Models


Models - 图1

Overview

A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.

Phalcon\Mvc\Model is the base for all models in a Phalcon application. It provides database independence, basicCRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services. Phalcon\Mvc\Model avoids the need of having to use SQL statements because it translatesmethods dynamically to the respective database engine operations.

Models are intended to work with the database on a high layer of abstraction. If you need to work with databases at a lower level check out the Phalcon\Db component documentation.

Creating Models

A model is a class that extends from Phalcon\Mvc\Model. Its class name should be in camel case notation:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class RobotParts extends Model
  5. {
  6. }

By default, the model Store\Toys\RobotParts will map to the table robot_parts. If you want to manually specify another name for the mapped table, you can use the setSource() method:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class RobotParts extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->setSource('toys_robot_parts');
  9. }
  10. }

The model RobotParts now maps to toys_robot_parts table. The initialize() method helps with setting up this model with a custom behavior i.e. a different table.

The initialize() method is only called once during the request. This method is intended to perform initializations that apply for all instances of the model created within the application. If you want to perform initialization tasks for every instance created you can use the onConstruct() method:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class RobotParts extends Model
  5. {
  6. public function onConstruct()
  7. {
  8. // ...
  9. }
  10. }

Public properties vs. Setters/Getters

Models can be implemented public properties, meaning that each property can be read/updated from any part of the code that has instantiated that model class:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public $price;
  9. }

Another implementation is to use getters and setter functions, which control which properties are publicly available for that model. The benefit of using getters and setters is that the developer can perform transformations and validation checks on the values set for the model, which is impossible when using public properties. Additionally getters and setters allow for future changes without changing the interface of the model class. So if a field name changes, the only change needed will be in the private property of the model referenced in the relevant getter/setter and nowhere else in the code.

  1. <?php
  2. namespace Store\Toys;
  3. use InvalidArgumentException;
  4. use Phalcon\Mvc\Model;
  5. class Robots extends Model
  6. {
  7. protected $id;
  8. protected $name;
  9. protected $price;
  10. public function getId()
  11. {
  12. return $this->id;
  13. }
  14. public function setName($name)
  15. {
  16. // The name is too short?
  17. if (strlen($name) < 10) {
  18. throw new InvalidArgumentException(
  19. 'The name is too short'
  20. );
  21. }
  22. $this->name = $name;
  23. }
  24. public function getName()
  25. {
  26. return $this->name;
  27. }
  28. public function setPrice($price)
  29. {
  30. // Negative prices aren't allowed
  31. if ($price < 0) {
  32. throw new InvalidArgumentException(
  33. "Price can't be negative"
  34. );
  35. }
  36. $this->price = $price;
  37. }
  38. public function getPrice()
  39. {
  40. // Convert the value to double before be used
  41. return (double) $this->price;
  42. }
  43. }

Public properties provide less complexity in development. However getters/setters can heavily increase the testability, extensibility and maintainability of applications. Developers can decide which strategy is more appropriate for the application they are creating, depending on the needs of the application. The ORM is compatible with both schemes of defining properties.

Underscores in property names can be problematic when using getters and setters.

If you use underscores in your property names, you must still use camel case in your getter/setter declarations for use with magic methods. (e.g. $model->getPropertyName instead of $model->getProperty_name, $model->findByPropertyName instead of $model->findByProperty_name, etc.). As much of the system expects camel case, and underscores are commonly removed, it is recommended to name your properties in the manner shown throughout the documentation. You can use a column map (as described above) to ensure proper mapping of your properties to their database counterparts.

Understanding Records To Objects

Every instance of a model represents a row in the table. You can easily access record data by reading object properties. For example, for a table ‘robots’ with the records:

  1. mysql> select * from robots;
  2. +----+------------+------------+------+
  3. | id | name | type | year |
  4. +----+------------+------------+------+
  5. | 1 | Robotina | mechanical | 1972 |
  6. | 2 | Astro Boy | mechanical | 1952 |
  7. | 3 | Terminator | cyborg | 2029 |
  8. +----+------------+------------+------+
  9. 3 rows in set (0.00 sec)

You could find a certain record by its primary key and then print its name:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Find record with id = 3
  4. $robot = Robots::findFirst(3);
  5. // Prints 'Terminator'
  6. echo $robot->name;

Once the record is in memory, you can make modifications to its data and then save changes:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(3);
  4. $robot->name = 'RoboCop';
  5. $robot->save();

As you can see, there is no need to use raw SQL statements. Phalcon\Mvc\Model provides high database abstraction for web applications.

Finding Records

Phalcon\Mvc\Model also offers several methods for querying records. The following examples will show you how to query one or more records from a model:

  1. <?php
  2. use Store\Toys\Robots;
  3. // How many robots are there?
  4. $robots = Robots::find();
  5. echo 'There are ', count($robots), "\n";
  6. // How many mechanical robots are there?
  7. $robots = Robots::find("type = 'mechanical'");
  8. echo 'There are ', count($robots), "\n";
  9. // Get and print virtual robots ordered by name
  10. $robots = Robots::find(
  11. [
  12. "type = 'virtual'",
  13. 'order' => 'name',
  14. ]
  15. );
  16. foreach ($robots as $robot) {
  17. echo $robot->name, "\n";
  18. }
  19. // Get first 100 virtual robots ordered by name
  20. $robots = Robots::find(
  21. [
  22. "type = 'virtual'",
  23. 'order' => 'name',
  24. 'limit' => 100,
  25. ]
  26. );
  27. foreach ($robots as $robot) {
  28. echo $robot->name, "\n";
  29. }

If you want find record by external data (such as user input) or variable data you must use Binding Parameters`.

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

  1. <?php
  2. use Store\Toys\Robots;
  3. // What's the first robot in robots table?
  4. $robot = Robots::findFirst();
  5. echo 'The robot name is ', $robot->name, "\n";
  6. // What's the first mechanical robot in robots table?
  7. $robot = Robots::findFirst("type = 'mechanical'");
  8. echo 'The first mechanical robot name is ', $robot->name, "\n";
  9. // Get first virtual robot ordered by name
  10. $robot = Robots::findFirst(
  11. [
  12. "type = 'virtual'",
  13. 'order' => 'name',
  14. ]
  15. );
  16. echo 'The first virtual robot name is ', $robot->name, "\n";

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

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(
  4. [
  5. "type = 'virtual'",
  6. 'order' => 'name DESC',
  7. 'limit' => 30,
  8. ]
  9. );
  10. $robots = Robots::find(
  11. [
  12. 'conditions' => 'type = ?1',
  13. 'bind' => [
  14. 1 => 'virtual',
  15. ]
  16. ]
  17. );

The available query options are:

ParameterDescriptionExample
conditionsSearch conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon\Mvc\Model assumes the first parameter are the conditions.'conditions' => "name LIKE 'steve%'"
columnsReturn specific columns instead of the full columns in the model. When using this option an incomplete object is returned'columns' => 'id, name'
bindBind is used together with options, by replacing placeholders and escaping values thus increasing security'bind' => ['status' => 'A', 'type' => 'some-time']
bindTypesWhen binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security'bindTypes' => [Column::BIND_PARAM_STR, Column::BIND_PARAM_INT]
orderIs used to sort the resultset. Use one or more fields separated by commas.'order' => 'name DESC, status'
limitLimit the results of the query to results to certain range'limit' => 10
offsetOffset the results of the query by a certain amount'offset' => 5
groupAllows to collect data across multiple records and group the results by one or more columns'group' => 'name, status'
for_updateWith this option, Phalcon\Mvc\Model reads the latest available data, setting exclusive locks on each row it reads'for_update' => true
shared_lockWith this option, Phalcon\Mvc\Model reads the latest available data, setting shared locks on each row it reads'shared_lock' => true
cacheCache the resultset, reducing the continuous access to the relational system'cache' => ['lifetime' => 3600, 'key' => 'my-find-key']
hydrationSets the hydration strategy to represent each returned record in the result'hydration' => Resultset::HYDRATE_OBJECTS

If you prefer, there is also available a way to create queries in an object-oriented way, instead of using an array of parameters:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robots = Robots::query()
  4. ->where('type = :type:')
  5. ->andWhere('year < 2000')
  6. ->bind(['type' => 'mechanical'])
  7. ->orderBy('name')
  8. ->execute();

The static method query() returns a Phalcon\Mvc\Model\Criteria object that is friendly with IDE autocompleters.

All the queries are internally handled as PHQL queries. PHQL is a high-level, object-oriented and SQL-like language. This language provide you more features to perform queries like joining other models, define groupings, add aggregations etc.

Lastly, there is the findFirstBy<property-name>() method. This method expands on the findFirst() method mentioned earlier. It allows you to quickly perform a retrieval from a table by using the property name in the method itself and passing it a parameter that contains the data you want to search for in that column. An example is in order, so taking our Robots model mentioned earlier:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public $price;
  9. }

We have three properties to work with here: $id, $name and $price. So, let’s say you want to retrieve the first record in the table with the name ‘Terminator’. This could be written like:

  1. <?php
  2. use Store\Toys\Robots;
  3. $name = 'Terminator';
  4. $robot = Robots::findFirstByName($name);
  5. if ($robot) {
  6. echo 'The first robot with the name ' . $name . ' cost ' . $robot->price . '.';
  7. } else {
  8. echo 'There were no robots found in our table with the name ' . $name . '.';
  9. }

Notice that we used ‘Name’ in the method call and passed the variable $name to it, which contains the name we are looking for in our table. Notice also that when we find a match with our query, all the other properties are available to us as well.

Model Resultsets

While findFirst() returns directly an instance of the called class (when there is data to be returned), the find() method returns a Phalcon\Mvc\Model\Resultset\Simple. This is an object that encapsulates all the functionality a resultset has like traversing, seeking specific records, counting, etc.

These objects are more powerful than standard arrays. One of the greatest features of the Phalcon\Mvc\Model\Resultset is that at any time there is only one record in memory. This greatly helps in memory management especially when working with large amounts of data.

  1. <?php
  2. use Store\Toys\Robots;
  3. // Get all robots
  4. $robots = Robots::find();
  5. // Traversing with a foreach
  6. foreach ($robots as $robot) {
  7. echo $robot->name, "\n";
  8. }
  9. // Traversing with a while
  10. $robots->rewind();
  11. while ($robots->valid()) {
  12. $robot = $robots->current();
  13. echo $robot->name, "\n";
  14. $robots->next();
  15. }
  16. // Count the resultset
  17. echo count($robots);
  18. // Alternative way to count the resultset
  19. echo $robots->count();
  20. // Move the internal cursor to the third robot
  21. $robots->seek(2);
  22. $robot = $robots->current();
  23. // Access a robot by its position in the resultset
  24. $robot = $robots[5];
  25. // Check if there is a record in certain position
  26. if (isset($robots[3])) {
  27. $robot = $robots[3];
  28. }
  29. // Get the first record in the resultset
  30. $robot = $robots->getFirst();
  31. // Get the last record
  32. $robot = $robots->getLast();

Phalcon’s resultsets emulate scrollable cursors, you can get any row just by accessing its position, or seeking the internal pointer to a specific position. Note that some database systems don’t support scrollable cursors, this forces to re-execute the query in order to rewind the cursor to the beginning and obtain the record at the requested position. Similarly, if a resultset is traversed several times, the query must be executed the same number of times.

As storing large query results in memory could consume many resources, resultsets are obtained from the database in chunks of 32 rows - reducing the need to re-execute the request in several cases.

Note that resultsets can be serialized and stored in a cache backend. Phalcon\Cache can help with that task. However, serializing data causes Phalcon\Mvc\Model to retrieve all the data from the database in an array, thus consuming more memory while this process takes place.

  1. <?php
  2. // Query all records from model parts
  3. $parts = Parts::find();
  4. // Store the resultset into a file
  5. file_put_contents(
  6. 'cache.txt',
  7. serialize($parts)
  8. );
  9. // Get parts from file
  10. $parts = unserialize(
  11. file_get_contents('cache.txt')
  12. );
  13. // Traverse the parts
  14. foreach ($parts as $part) {
  15. echo $part->id;
  16. }

Custom Resultsets

There are times that the application logic requires additional manipulation of the data as it is retrieved from the database. Previously, we would just extend the model and encapsulate the functionality in a class in the model or a trait, returning back to the caller usually an array of transformed data.

With custom resultsets, you no longer need to do that. The custom resultset will encapsulate the functionality that otherwise would be in the model and can be reused by other models, thus keeping the code DRY. This way, the find() method will no longer return the default Phalcon\Mvc\Model\Resultset, but instead the custom one. Phalcon allows you to do this by using the getResultsetClass() in your model.

First we need to define the resultset class:

  1. <?php
  2. namespace Application\Mvc\Model\Resultset;
  3. use \Phalcon\Mvc\Model\Resultset\Simple;
  4. class Custom extends Simple
  5. {
  6. public function getSomeData() {
  7. /** CODE */
  8. }
  9. }

In the model, we set the class in the getResultsetClass() as follows:

  1. <?php
  2. namespace Phalcon\Test\Models\Statistics;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->setSource('robots');
  9. }
  10. public function getResultsetClass()
  11. {
  12. return \Application\Mvc\Model\Resultset\Custom::class;
  13. }
  14. }

and finally in your code you will have something like this:

  1. <?php
  2. /**
  3. * Find the robots
  4. */
  5. $robots = Robots::find(
  6. [
  7. 'conditions' => 'date between "2017-01-01" AND "2017-12-31"',
  8. 'order' => 'date',
  9. ]
  10. );
  11. /**
  12. * Pass the data to the view
  13. */
  14. $this->view->mydata = $robots->getSomeData();

Filtering Resultsets

The most efficient way to filter data is setting some search criteria, databases will use indexes set on tables to return data faster. Phalcon additionally allows you to filter the data using PHP using any resource that is not available in the database:

  1. <?php
  2. $customers = Customers::find();
  3. $customers = $customers->filter(
  4. function ($customer) {
  5. // Return only customers with a valid e-mail
  6. if (filter_var($customer->email, FILTER_VALIDATE_EMAIL)) {
  7. return $customer;
  8. }
  9. }
  10. );

Binding Parameters

Bound parameters are also supported in Phalcon\Mvc\Model. You are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Query robots binding parameters with string placeholders
  4. // Parameters whose keys are the same as placeholders
  5. $robots = Robots::find(
  6. [
  7. 'name = :name: AND type = :type:',
  8. 'bind' => [
  9. 'name' => 'Robotina',
  10. 'type' => 'maid',
  11. ],
  12. ]
  13. );
  14. // Query robots binding parameters with integer placeholders
  15. $robots = Robots::find(
  16. [
  17. 'name = ?1 AND type = ?2',
  18. 'bind' => [
  19. 1 => 'Robotina',
  20. 2 => 'maid',
  21. ],
  22. ]
  23. );
  24. // Query robots binding parameters with both string and integer placeholders
  25. // Parameters whose keys are the same as placeholders
  26. $robots = Robots::find(
  27. [
  28. 'name = :name: AND type = ?1',
  29. 'bind' => [
  30. 'name' => 'Robotina',
  31. 1 => 'maid',
  32. ],
  33. ]
  34. );

When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case '1' or '2' are considered strings and not numbers, so the placeholder could not be successfully replaced.

Strings are automatically escaped using PDO. This function takes into account the connection charset, so its recommended to define the correct charset in the connection parameters or in the database configuration, as a wrong charset will produce undesired effects when storing or retrieving data.

Additionally you can set the parameter bindTypes, this allows defining how the parameters should be bound according to its data type:

  1. <?php
  2. use Phalcon\Db\Column;
  3. use Store\Toys\Robots;
  4. // Bind parameters
  5. $parameters = [
  6. 'name' => 'Robotina',
  7. 'year' => 2008,
  8. ];
  9. // Casting Types
  10. $types = [
  11. 'name' => Column::BIND_PARAM_STR,
  12. 'year' => Column::BIND_PARAM_INT,
  13. ];
  14. // Query robots binding parameters with string placeholders
  15. $robots = Robots::find(
  16. [
  17. 'name = :name: AND year = :year:',
  18. 'bind' => $parameters,
  19. 'bindTypes' => $types,
  20. ]
  21. );

Since the default bind-type is Phalcon\Db\Column::BIND_PARAM_STR, there is no need to specify the ‘bindTypes’ parameter if all of the columns are of that type.

If you bind arrays in bound parameters, keep in mind, that keys must be numbered from zero:

  1. <?php
  2. use Store\Toys\Robots;
  3. $array = ['a', 'b', 'c']; // $array: [[0] => 'a', [1] => 'b', [2] => 'c']
  4. unset($array[1]); // $array: [[0] => 'a', [2] => 'c']
  5. // Now we have to renumber the keys
  6. $array = array_values($array); // $array: [[0] => 'a', [1] => 'c']
  7. $robots = Robots::find(
  8. [
  9. 'letter IN ({letter:array})',
  10. 'bind' => [
  11. 'letter' => $array,
  12. ],
  13. ]
  14. );

Bound parameters are available for all query methods such as find() and findFirst() but also the calculation methods like count(), sum(), average() etc.

If you’re using “finders” e.g. find(), findFirst(), etc., bound parameters are automatically used:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Explicit query using bound parameters
  4. $robots = Robots::find(
  5. [
  6. 'name = ?0',
  7. 'bind' => [
  8. 'Ultron',
  9. ],
  10. ]
  11. );
  12. // Implicit query using bound parameters
  13. $robots = Robots::findByName('Ultron');

Initializing/Preparing fetched records

May be the case that after obtaining a record from the database is necessary to initialise the data before being used by the rest of the application. You can implement the afterFetch() method in a model, this event will be executed just after create the instance and assign the data to it:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public $status;
  9. public function beforeSave()
  10. {
  11. // Convert the array into a string
  12. $this->status = join(',', $this->status);
  13. }
  14. public function afterFetch()
  15. {
  16. // Convert the string to an array
  17. $this->status = explode(',', $this->status);
  18. }
  19. public function afterSave()
  20. {
  21. // Convert the string to an array
  22. $this->status = explode(',', $this->status);
  23. }
  24. }

If you use getters/setters instead of/or together with public properties, you can initialize the field once it is accessed:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public $status;
  9. public function getStatus()
  10. {
  11. return explode(',', $this->status);
  12. }
  13. }

Generating Calculations

Calculations (or aggregations) are helpers for commonly used functions of database systems such as COUNT, SUM, MAX, MIN or AVG. Phalcon\Mvc\Model allows to use these functions directly from the exposed methods.

Count examples:

  1. <?php
  2. // How many employees are?
  3. $rowcount = Employees::count();
  4. // How many different areas are assigned to employees?
  5. $rowcount = Employees::count(
  6. [
  7. 'distinct' => 'area',
  8. ]
  9. );
  10. // How many employees are in the Testing area?
  11. $rowcount = Employees::count(
  12. 'area = "Testing"'
  13. );
  14. // Count employees grouping results by their area
  15. $group = Employees::count(
  16. [
  17. 'group' => 'area',
  18. ]
  19. );
  20. foreach ($group as $row) {
  21. echo 'There are ', $row->rowcount, ' in ', $row->area;
  22. }
  23. // Count employees grouping by their area and ordering the result by count
  24. $group = Employees::count(
  25. [
  26. 'group' => 'area',
  27. 'order' => 'rowcount',
  28. ]
  29. );
  30. // Avoid SQL injections using bound parameters
  31. $group = Employees::count(
  32. [
  33. 'type > ?0',
  34. 'bind' => [
  35. $type,
  36. ],
  37. ]
  38. );

Sum examples:

  1. <?php
  2. // How much are the salaries of all employees?
  3. $total = Employees::sum(
  4. [
  5. 'column' => 'salary',
  6. ]
  7. );
  8. // How much are the salaries of all employees in the Sales area?
  9. $total = Employees::sum(
  10. [
  11. 'column' => 'salary',
  12. 'conditions' => "area = 'Sales'",
  13. ]
  14. );
  15. // Generate a grouping of the salaries of each area
  16. $group = Employees::sum(
  17. [
  18. 'column' => 'salary',
  19. 'group' => 'area',
  20. ]
  21. );
  22. foreach ($group as $row) {
  23. echo 'The sum of salaries of the ', $row->area, ' is ', $row->sumatory;
  24. }
  25. // Generate a grouping of the salaries of each area ordering
  26. // salaries from higher to lower
  27. $group = Employees::sum(
  28. [
  29. 'column' => 'salary',
  30. 'group' => 'area',
  31. 'order' => 'sumatory DESC',
  32. ]
  33. );
  34. // Avoid SQL injections using bound parameters
  35. $group = Employees::sum(
  36. [
  37. 'conditions' => 'area > ?0',
  38. 'bind' => [
  39. $area,
  40. ],
  41. ]
  42. );

Average examples:

  1. <?php
  2. // What is the average salary for all employees?
  3. $average = Employees::average(
  4. [
  5. 'column' => 'salary',
  6. ]
  7. );
  8. // What is the average salary for the Sales's area employees?
  9. $average = Employees::average(
  10. [
  11. 'column' => 'salary',
  12. 'conditions' => "area = 'Sales'",
  13. ]
  14. );
  15. // Avoid SQL injections using bound parameters
  16. $average = Employees::average(
  17. [
  18. 'column' => 'age',
  19. 'conditions' => 'area > ?0',
  20. 'bind' => [
  21. $area,
  22. ],
  23. ]
  24. );

Max/Min examples:

  1. <?php
  2. // What is the oldest age of all employees?
  3. $age = Employees::maximum(
  4. [
  5. 'column' => 'age',
  6. ]
  7. );
  8. // What is the oldest of employees from the Sales area?
  9. $age = Employees::maximum(
  10. [
  11. 'column' => 'age',
  12. 'conditions' => "area = 'Sales'",
  13. ]
  14. );
  15. // What is the lowest salary of all employees?
  16. $salary = Employees::minimum(
  17. [
  18. 'column' => 'salary',
  19. ]
  20. );

Creating/Updating Records

The Phalcon\Mvc\Model::save() method allows you to create/update records according to whether they already exist in the table associated with a model. The save method is called internally by the create and update methods of Phalcon\Mvc\Model. For this to work as expected it is necessary to have properly defined a primary key in the entity to determine whether a record should be updated or created.

Also the method executes associated validators, virtual foreign keys and events that are defined in the model:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->type = 'mechanical';
  5. $robot->name = 'Astro Boy';
  6. $robot->year = 1952;
  7. if ($robot->save() === false) {
  8. echo "Umh, We can't store robots right now: \n";
  9. $messages = $robot->getMessages();
  10. foreach ($messages as $message) {
  11. echo $message, "\n";
  12. }
  13. } else {
  14. echo 'Great, a new robot was saved successfully!';
  15. }

An array could be passed to assign() to avoid assign every column manually. Phalcon\Mvc\Model will check if there are setters implemented for the columns passed in the array giving priority to them instead of assign directly the values of the attributes:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->assign(
  5. [
  6. 'type' => 'mechanical',
  7. 'name' => 'Astro Boy',
  8. 'year' => 1952,
  9. ]
  10. );
  11. $robots->save();

Values assigned directly or via the array of attributes are escaped/sanitized according to the related attribute data type. So you can pass an insecure array without worrying about possible SQL injections:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->assign($_POST);
  5. $robot->save();

Without precautions mass assignment could allow attackers to set any database column’s value. Only use this feature if you want to permit a user to insert/update every column in the model, even if those fields are not in the submitted form.

You can set an additional parameter in save to set a whitelist of fields that only must taken into account when doing the mass assignment:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->assign(
  5. $_POST,
  6. [
  7. 'name',
  8. 'type',
  9. ]
  10. );
  11. $robot->save();

Create/Update with Confidence

When an application has a lot of competition, we could be expecting create a record but it is actually updated. This could happen if we use Phalcon\Mvc\Model::save() to persist the records in the database. If we want to be absolutely sure that a record is created or updated, we can change the save() call with create() or update():

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->type = 'mechanical';
  5. $robot->name = 'Astro Boy';
  6. $robot->year = 1952;
  7. // This record only must be created
  8. if ($robot->create() === false) {
  9. echo "Umh, We can't store robots right now: \n";
  10. $messages = $robot->getMessages();
  11. foreach ($messages as $message) {
  12. echo $message, "\n";
  13. }
  14. } else {
  15. echo 'Great, a new robot was created successfully!';
  16. }

The methods create and update also accept an array of values as parameter.

Deleting Records

The Phalcon\Mvc\Model::delete() method allows to delete a record. You can use it as follows:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(11);
  4. if ($robot !== false) {
  5. if ($robot->delete() === false) {
  6. echo "Sorry, we can't delete the robot right now: \n";
  7. $messages = $robot->getMessages();
  8. foreach ($messages as $message) {
  9. echo $message, "\n";
  10. }
  11. } else {
  12. echo 'The robot was deleted successfully!';
  13. }
  14. }

You can also delete many records by traversing a resultset with a foreach:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robots = Robots::find(
  4. "type = 'mechanical'"
  5. );
  6. foreach ($robots as $robot) {
  7. if ($robot->delete() === false) {
  8. echo "Sorry, we can't delete the robot right now: \n";
  9. $messages = $robot->getMessages();
  10. foreach ($messages as $message) {
  11. echo $message, "\n";
  12. }
  13. } else {
  14. echo 'The robot was deleted successfully!';
  15. }
  16. }

The following events are available to define custom business rules that can be executed when a delete operation is performed:

OperationNameCan stop operation?Explanation
DeletingafterDeleteNoRuns after the delete operation was made
DeletingbeforeDeleteYesRuns before the delete operation is made

With the above events can also define business rules in the models:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function beforeDelete()
  7. {
  8. if ($this->status === 'A') {
  9. echo "The robot is active, it can't be deleted";
  10. return false;
  11. }
  12. return true;
  13. }
  14. }

Hydration Modes

As mentioned previously, resultsets are collections of complete objects, this means that every returned result is an object representing a row in the database. These objects can be modified and saved again to persistence:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robots = Robots::find();
  4. // Manipulating a resultset of complete objects
  5. foreach ($robots as $robot) {
  6. $robot->year = 2000;
  7. $robot->save();
  8. }

Sometimes records are obtained only to be presented to a user in read-only mode, in these cases it may be useful to change the way in which records are represented to facilitate their handling. The strategy used to represent objects returned in a resultset is called ‘hydration mode’:

  1. <?php
  2. use Phalcon\Mvc\Model\Resultset;
  3. use Store\Toys\Robots;
  4. $robots = Robots::find();
  5. // Return every robot as an array
  6. $robots->setHydrateMode(
  7. Resultset::HYDRATE_ARRAYS
  8. );
  9. foreach ($robots as $robot) {
  10. echo $robot['year'], PHP_EOL;
  11. }
  12. // Return every robot as a stdClass
  13. $robots->setHydrateMode(
  14. Resultset::HYDRATE_OBJECTS
  15. );
  16. foreach ($robots as $robot) {
  17. echo $robot->year, PHP_EOL;
  18. }
  19. // Return every robot as a Robots instance
  20. $robots->setHydrateMode(
  21. Resultset::HYDRATE_RECORDS
  22. );
  23. foreach ($robots as $robot) {
  24. echo $robot->year, PHP_EOL;
  25. }

Hydration mode can also be passed as a parameter of find:

  1. <?php
  2. use Phalcon\Mvc\Model\Resultset;
  3. use Store\Toys\Robots;
  4. $robots = Robots::find(
  5. [
  6. 'hydration' => Resultset::HYDRATE_ARRAYS,
  7. ]
  8. );
  9. foreach ($robots as $robot) {
  10. echo $robot['year'], PHP_EOL;
  11. }

Table prefixes

If you want all your tables to have certain prefix and without setting source in all models you can use the Phalcon\Mvc\Model\Manager and the method setModelPrefix():

  1. <?php
  2. use Phalcon\Mvc\Model\Manager;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. }
  7. $manager = new Manager();
  8. $manager->setModelPrefix('wp_');
  9. $robots = new Robots(null, null, $manager);
  10. echo $robots->getSource(); // will return wp_robots

Auto-generated identity columns

Some models may have identity columns. These columns usually are the primary key of the mapped table. Phalcon\Mvc\Model can recognize the identity column omitting it in the generated SQL INSERT, so the database system can generate an auto-generated value for it. Always after creating a record, the identity field will be registered with the value generated in the database system for it:

  1. <?php
  2. $robot->save();
  3. echo 'The generated id is: ', $robot->id;

Phalcon\Mvc\Model is able to recognize the identity column. Depending on the database system, those columns may be serial columns like in PostgreSQL or auto_increment columns in the case of MySQL.

PostgreSQL uses sequences to generate auto-numeric values, by default, Phalcon tries to obtain the generated value from the sequence table_field_seq, for example: robots_id_seq, if that sequence has a different name, the getSequenceName() method needs to be implemented:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function getSequenceName()
  7. {
  8. return 'robots_sequence_name';
  9. }
  10. }

Skipping Columns

To tell Phalcon\Mvc\Model that always omits some fields in the creation and/or update of records in order to delegate the database system the assignation of the values by a trigger or a default:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. // Skips fields/columns on both INSERT/UPDATE operations
  9. $this->skipAttributes(
  10. [
  11. 'year',
  12. 'price',
  13. ]
  14. );
  15. // Skips only when inserting
  16. $this->skipAttributesOnCreate(
  17. [
  18. 'created_at',
  19. ]
  20. );
  21. // Skips only when updating
  22. $this->skipAttributesOnUpdate(
  23. [
  24. 'modified_in',
  25. ]
  26. );
  27. }
  28. }

This will ignore globally these fields on each INSERT/UPDATE operation on the whole application. If you want to ignore different attributes on different INSERT/UPDATE operations, you can specify the second parameter (boolean) - true for replacement. Forcing a default value can be done as follows:

  1. <?php
  2. use Store\Toys\Robots;
  3. use Phalcon\Db\RawValue;
  4. $robot = new Robots();
  5. $robot->name = 'Bender';
  6. $robot->year = 1999;
  7. $robot->created_at = new RawValue('default');
  8. $robot->create();

A callback also can be used to create a conditional assignment of automatic default values:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Db\RawValue;
  5. class Robots extends Model
  6. {
  7. public function beforeCreate()
  8. {
  9. if ($this->price > 10000) {
  10. $this->type = new RawValue('default');
  11. }
  12. }
  13. }

Never use a Phalcon\Db\RawValue to assign external data (such as user input) or variable data. The value of these fields is ignored when binding parameters to the query. So it could be used to attack the application injecting SQL.

Dynamic Updates

SQL UPDATE statements are by default created with every column defined in the model (full all-field SQL update). You can change specific models to make dynamic updates, in this case, just the fields that had changed are used to create the final SQL statement.

In some cases this could improve the performance by reducing the traffic between the application and the database server, this specially helps when the table has blob/text fields:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->useDynamicUpdate(true);
  9. }
  10. }

Independent Column Mapping

The ORM supports an independent column map, which allows the developer to use different column names in the model to the ones in the table. Phalcon will recognize the new column names and will rename them accordingly to match the respective columns in the database. This is a great feature when one needs to rename fields in the database without having to worry about all the queries in the code. A change in the column map in the model will take care of the rest. For example:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $code;
  7. public $theName;
  8. public $theType;
  9. public $theYear;
  10. public function columnMap()
  11. {
  12. // Keys are the real names in the table and
  13. // the values their names in the application
  14. return [
  15. 'id' => 'code',
  16. 'the_name' => 'theName',
  17. 'the_type' => 'theType',
  18. 'the_year' => 'theYear',
  19. ];
  20. }
  21. }

Then you can use the new names naturally in your code:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Find a robot by its name
  4. $robot = Robots::findFirst(
  5. "theName = 'Voltron'"
  6. );
  7. echo $robot->theName, "\n";
  8. // Get robots ordered by type
  9. $robot = Robots::find(
  10. [
  11. 'order' => 'theType DESC',
  12. ]
  13. );
  14. foreach ($robots as $robot) {
  15. echo 'Code: ', $robot->code, "\n";
  16. }
  17. // Create a robot
  18. $robot = new Robots();
  19. $robot->code = '10101';
  20. $robot->theName = 'Bender';
  21. $robot->theType = 'Industrial';
  22. $robot->theYear = 2999;
  23. $robot->save();

Consider the following when renaming your columns:

  • References to attributes in relationships/validators must use the new names
  • Refer the real column names will result in an exception by the ORMThe independent column map allows you to:

  • Write applications using your own conventions

  • Eliminate vendor prefixes/suffixes in your code
  • Change column names without change your application code

Record Snapshots

Specific models could be set to maintain a record snapshot when they’re queried. You can use this feature to implement auditing or just to know what fields are changed according to the data queried from the persistence:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->keepSnapshots(true);
  9. }
  10. }

When activating this feature the application consumes a bit more of memory to keep track of the original values obtained from the persistence. In models that have this feature activated you can check what fields changed as follows:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Get a record from the database
  4. $robot = Robots::findFirst();
  5. // Change a column
  6. $robot->name = 'Other name';
  7. var_dump($robot->getChangedFields()); // ['name']
  8. var_dump($robot->hasChanged('name')); // true
  9. var_dump($robot->hasChanged('type')); // false

Snapshots are updated on model creation/update. Using hasUpdated() and getUpdatedFields() can be used to check if fields were updated after a create/save/update but it could potentially cause problems to your application if you execute getChangedFields() in afterUpdate(), afterSave() or afterCreate().

You can disable this functionality by using:

  1. Phalcon\Mvc\Model::setup(
  2. [
  3. 'updateSnapshotOnSave' => false,
  4. ]
  5. );

or if you prefer set this in your php.ini

  1. phalcon.orm.update_snapshot_on_save = 0

Using this functionality will have the following effect:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class User extends Model
  4. {
  5. public function initialize()
  6. {
  7. $this->keepSnapshots(true);
  8. }
  9. }
  10. $user = new User();
  11. $user->name = 'Test User';
  12. $user->create();
  13. var_dump(
  14. $user->getChangedFields()
  15. );
  16. $user->login = 'testuser';
  17. var_dump(
  18. $user->getChangedFields()
  19. );
  20. $user->update();
  21. var_dump(
  22. $user->getChangedFields()
  23. );

On Phalcon 4.0.0 and later it is:

  1. array(0) {
  2. }
  3. array(1) {
  4. [0]=>
  5. string(5) "login"
  6. }
  7. array(0) {
  8. }

getUpdatedFields() will properly return updated fields or as mentioned above you can go back to the previous behavior by setting the relevant ini value.

Pointing to a different schema

If a model is mapped to a table that is in a different schemas/databases than the default. You can use the setSchema() method to define that:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->setSchema('toys');
  9. }
  10. }

Setting multiple databases

In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Model needs to connect to the database it requests the db service in the application’s services container. You can overwrite this service setting it in the initialize() method:

  1. <?php
  2. use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
  3. use Phalcon\Db\Adapter\Pdo\PostgreSQL as PostgreSQLPdo;
  4. // This service returns a MySQL database
  5. $di->set(
  6. 'dbMysql',
  7. function () {
  8. return new MysqlPdo(
  9. [
  10. 'host' => 'localhost',
  11. 'username' => 'root',
  12. 'password' => 'secret',
  13. 'dbname' => 'invo',
  14. ]
  15. );
  16. }
  17. );
  18. // This service returns a PostgreSQL database
  19. $di->set(
  20. 'dbPostgres',
  21. function () {
  22. return new PostgreSQLPdo(
  23. [
  24. 'host' => 'localhost',
  25. 'username' => 'postgres',
  26. 'password' => '',
  27. 'dbname' => 'invo',
  28. ]
  29. );
  30. }
  31. );

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

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->setConnectionService('dbPostgres');
  9. }
  10. }

But Phalcon offers you more flexibility, you can define the connection that must be used to read and for write. This is specially useful to balance the load to your databases implementing a master-slave architecture:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function initialize()
  7. {
  8. $this->setReadConnectionService('dbSlave');
  9. $this->setWriteConnectionService('dbMaster');
  10. }
  11. }

The ORM also provides Horizontal Sharding facilities, by allowing you to implement a ‘shard’ selection according to the current query conditions:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. /**
  7. * Dynamically selects a shard
  8. *
  9. * @param array $intermediate
  10. * @param array $bindParams
  11. * @param array $bindTypes
  12. */
  13. public function selectReadConnection($intermediate, $bindParams, $bindTypes)
  14. {
  15. // Check if there is a 'where' clause in the select
  16. if (isset($intermediate['where'])) {
  17. $conditions = $intermediate['where'];
  18. // Choose the possible shard according to the conditions
  19. if ($conditions['left']['name'] === 'id') {
  20. $id = $conditions['right']['value'];
  21. if ($id > 0 && $id < 10000) {
  22. return $this->getDI()->get('dbShard1');
  23. }
  24. if ($id > 10000) {
  25. return $this->getDI()->get('dbShard2');
  26. }
  27. }
  28. }
  29. // Use a default shard
  30. return $this->getDI()->get('dbShard0');
  31. }
  32. }

The selectReadConnection() method is called to choose the right connection, this method intercepts any new query executed:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst('id = 101');

Injecting services into Models

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

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function notSaved()
  7. {
  8. // Obtain the flash service from the DI container
  9. $flash = $this->getDI()->getFlash();
  10. $messages = $this->getMessages();
  11. // Show validation messages
  12. foreach ($messages as $message) {
  13. $flash->error($message);
  14. }
  15. }
  16. }

The notSaved event is triggered every time that a create or update action fails. So 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 save.

Disabling/Enabling Features

In the ORM we have implemented a mechanism that allow you to enable/disable specific features or options globally on the fly. According to how you use the ORM you can disable that you aren’t using. These options can also be temporarily disabled if required:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. Model::setup(
  4. [
  5. 'events' => false,
  6. 'columnRenaming' => false,
  7. ]
  8. );

The available options are:

OptionDescriptionDefault
astCacheEnables/Disables callbacks, hooks and event notifications from all the modelsnull
cacheLevelSets the cache level for the ORM3
castOnHydrate false
columnRenamingEnables/Disables the column renamingtrue
disableAssignSettersAllow disabling setters in your modelfalse
enableImplicitJoins true
enableLiterals true
escapeIdentifiers true
eventsEnables/Disables callbacks, hooks and event notifications from all the modelstrue
exceptionOnFailedSaveEnables/Disables throwing an exception when there is a failed save()false
forceCasting false
ignoreUnknownColumnsEnables/Disables ignoring unknown columns on the modelfalse
lateStateBindingEnables/Disables late state binding of the Phalcon\Mvc\Model::cloneResultMap() methodfalse
notNullValidationsThe ORM automatically validate the not null columns present in the mapped tabletrue
parserCache null
phqlLiteralsEnables/Disables literals in the PHQL parsertrue
uniqueCacheId 3
updateSnapshotOnSaveEnables/Disables updating snapshots on save()true
virtualForeignKeysEnables/Disables the virtual foreign keystrue

NOTE Phalcon\Mvc\Model::assign() (which is used also when creating/updating/saving model) is always using setters if they exist when have data arguments passed, even when it’s required or necessary. This will add some additional overhead to your application. You can change this behavior by adding phalcon.orm.disable_assign_setters = 1 to your ini file, it will just simply use $this->property = value.

Stand-Alone component

Using Phalcon\Mvc\Model in a stand-alone mode can be demonstrated below:

  1. <?php
  2. use Phalcon\Di;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Manager as ModelsManager;
  5. use Phalcon\Db\Adapter\Pdo\Sqlite as Connection;
  6. use Phalcon\Mvc\Model\Metadata\Memory as MetaData;
  7. $di = new Di();
  8. // Setup a connection
  9. $di->set(
  10. 'db',
  11. new Connection(
  12. [
  13. 'dbname' => 'sample.db',
  14. ]
  15. )
  16. );
  17. // Set a models manager
  18. $di->set(
  19. 'modelsManager',
  20. new ModelsManager()
  21. );
  22. // Use the memory meta-data adapter or other
  23. $di->set(
  24. 'modelsMetadata',
  25. new MetaData()
  26. );
  27. // Create a model
  28. class Robots extends Model
  29. {
  30. }
  31. // Use the model
  32. echo Robots::count();