Working with Models (Advanced)

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. }

自动生成标识列(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 in the following way:

  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 Update)

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();

Take into consideration the following the next 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 ORM

The independent column map allow 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:

  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

设置模式(Pointing to a different schema)

如果一个模型映射到一个在非默认的schemas/数据库中的表,你可以通过 setSchema() 方法去定义它:

  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)

在Phalcon中,所有模型可以属于同一个数据库连接,也可以分属独立的数据库连接。实际上,当 Phalcon\Mvc\Model 需要连接数据库的时候,它在应用服务容器内请求”db”这个服务。 可以通过在 initialize() 方法内重写这个服务的设置。

  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. );

然后,在 initialize() 方法内,我们为这个模型定义数据库连接。

  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. }

另外Phalcon还提供了更多的灵活性,你可分别定义用来读取和写入的数据库连接。这对实现主从架构的数据库负载均衡非常有用。 (译者注:EvaEngine项目为使用Phalcon提供了更多的灵活性,推荐了解和使用)

  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. }

另外ORM还可以通过根据当前查询条件来实现一个 ‘shard’ 选择器,来实现水平切分的功能。

  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. }

selectReadConnection() 方法用来选择正确的数据库连接,这个方法拦截任何新的查询操作:

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

注入服务到模型(Injecting services into Models)

你可能需要在模型中用到应用中注入的服务,下面的例子会教你如何去做:

  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. }

每当 “create” 或者 “update” 操作失败时会触发 “notSave” 事件。所以我们从DI中获取 “flash” 服务并推送确认消息。这样的话,我们不需要每次在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
eventsEnables/Disables callbacks, hooks and event notifications from all the modelstrue
columnRenamingEnables/Disables the column renamingtrue
notNullValidationsThe ORM automatically validate the not null columns present in the mapped tabletrue
virtualForeignKeysEnables/Disables the virtual foreign keystrue
phqlLiteralsEnables/Disables literals in the PHQL parsertrue
lateStateBindingEnables/Disables late state binding of the Mvc\Model::cloneResultMap() methodfalse

独立的组件(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();