使用模型(Working with Models)

模型代表了应用程序中的信息(数据)和处理数据的规则。模型主要用于管理与相应数据库表进行交互的规则。 大多数情况中,在应用程序中,数据库中每个表将对应一个模型。 应用程序中的大部分业务逻辑都将集中在模型里。

Phalcon\Mvc\Model 是 Phalcon 应用程序中所有模型的基类。它保证了数据库的独立性,基本的 CURD 操作, 高级的查询功能,多表关联等功能。 Phalcon\Mvc\Model 不需要直接使用 SQL 语句,因为它的转换方法,会动态的调用相应的数据库引擎进行处理。

模型是数据库的高级抽象层。如果您想进行低层次的数据库操作,您可以查看 Phalcon\Db 组件文档。

创建模型

模型是一个继承自 Phalcon\Mvc\Model 的一个类。时它的类名必须符合驼峰命名法:

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

如果使用 PHP 5.4/5.5 建议在模型中预先定义好所有的列,这样可以减少模型内存的开销以及内存分配。

默认情况下,模型 “Store\Toys\RobotParts” 对应的是数据库表 “robot_parts”, 如果想映射到其他数据库表,可以使用 setSource() 方法:

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

模型 RobotParts 现在映射到了 “toys_robot_parts” 表。initialize() 方法可以帮助在模型中建立自定义行为,例如指定不同的数据库表。

initialize() 方法在请求期间仅会被调用一次,目的是为应用中所有该模型的实例进行初始化。如果需要为每一个实例在创建的时候单独进行初始化, 可以使用 onConstruct() 事件:

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

公共属性对比设置与取值 Setters/Getters(Public properties vs. Setters/Getters)

模型可以通过公共属性的方式实现,意味着模型的所有属性在实例化该模型的地方可以无限制的读取和更新。

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

通过使用 getters/setters 方法,可以控制哪些属性可以公开访问,并且对属性值执行不同的形式的转换,同时可以保存在模型中的数据添加相应的验证规则。

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

公共属性的方式可以在开发中降低复杂度。而 getters/setters 的实现方式可以显著的增强应用的可测试性、扩展性和可维护性。 开发人员可以自己决定哪一种策略更加适合自己开发的应用。ORM同时兼容这两种方法。

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)

每个模型的实例对应一条数据表中的记录。可以方便的通过读取对象的属性来访问相应的数据。比如, 一个表 “robots” 有如下数据:

  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)

你可以通过主键找到某一条记录并且打印它的名称:

  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;

一旦记录被加载到内存中之后,你可以修改它的数据并保存所做的修改:

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

如上所示,不需要写任何SQL语句。Phalcon\Mvc\Model 为web应用提供了高层数据库抽象。

查找记录(Finding Records)

Phalcon\Mvc\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. }

如果需要通过外部数据(比如用户输入)或变量来查询记录,则必须要用`Binding Parameters`(绑定参数)的方式来防止SQL注入.

你可以使用 findFirst() 方法获取第一条符合查询条件的结果:

  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";

find()findFirst() 方法都接受关联数组作为查询条件:

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

可用的查询选项如下:

参数描述举例
conditions查询操作的搜索条件。用于提取只有那些满足指定条件的记录。默认情况下 Phalcon\Mvc\Model 假定第一个参数就是查询条件。“conditions” => “name LIKE ‘steve%’”
columns只返回指定的字段,而不是模型所有的字段。 当用这个选项时,返回的是一个不完整的对象。“columns” => “id, name”
bind绑定与选项一起使用,通过替换占位符以及转义字段值从而增加安全性。“bind” => [“status” => “A”, “type” => “some-time”]
bindTypes当绑定参数时,可以使用这个参数为绑定参数定义额外的类型限制从而更加增强安全性。“bindTypes” => [Column::BIND_PARAM_STR, Column::BIND_PARAM_INT]
order用于结果排序。使用一个或者多个字段,逗号分隔。“order” => “name DESC, status”
limit限制查询结果的数量在一定范围内。“limit” => 10
offsetOffset the results of the query by a certain amount“offset” => 5
group从多条记录中获取数据并且根据一个或多个字段对结果进行分组。“group” => “name, status”
for_update通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置独占锁。“for_update” => true
shared_lock通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置共享锁。“shared_lock” => true
cache缓存结果集,减少了连续访问数据库。“cache” => [“lifetime” => 3600, “key” => “my-find-key”]
hydrationSets the hydration strategy to represent each returned record in the result“hydration” => Resultset::HYDRATE_OBJECTS

如果你愿意,除了使用数组作为查询参数外,还可以通过一种面向对象的方式来创建查询:

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

静态方法 query() 返回一个对IDE自动完成友好的 Phalcon\Mvc\Model\Criteria 对象。

所有查询在内部都以 PHQL 查询的方式处理。PHQL是一个高层的、面向对象的类SQL语言。通过PHQL语言你可以使用更多的比如join其他模型、定义分组、添加聚集等特性。

最后,还有一个 findFirstBy<property-name>() 方法。这个方法扩展了前面提及的 findFirst() 方法。它允许您利用方法名中的属性名称,通过将要搜索的该字段的内容作为参数传给它,来快速从一个表执行检索操作。

还是用上面用过的 Robots 模型来举例说明:

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

我们这里有3个属性:$id, $name$price。因此,我们以想要查询第一个名称为 ‘Terminator’ 的记录为例,可以这样写:

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

请注意我们在方法调用中用的是 ‘Name’,并向它传递了变量 $name$name 的值就是我们想要找的记录的名称。另外注意,当我们的查询找到了符合的记录后,这个记录的其他属性也都是可用的。

模型结果集(Model Resultsets)

findFirst() 方法直接返回一个被调用对象的实例(如果有结果返回的话),而 find() 方法返回一个 Phalcon\Mvc\Model\Resultset\Simple 对象。这个对象也封装进了所有结果集的功能,比如遍历、查找特定的记录、统计等等。

这些对象比一般数组功能更强大。最大的特点是 Phalcon\Mvc\Model\Resultset 每时每刻只有一个结果在内存中。这对操作大数据量时的内存管理相当有帮助。

  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 的结果集模拟了可滚动的游标,你可以通过位置,或者内部指针去访问任何一条特定的记录。注意有一些数据库系统不支持滚动游标,这就使得查询会被重复执行, 以便回放光标到最开始的位置,然后获得相应的记录。类似地,如果多次遍历结果集,那么必须执行相同的查询次数。

将大数据量的查询结果存储在内存会消耗很多资源,正因为如此,分成每32行一块从数据库中获得结果集,以减少重复执行查询请求的次数,在一些情况下也节省内存。

注意结果集可以序列化后保存在一个后端缓存里面。 Phalcon\Cache 可以用来实现这个。但是,序列化数据会导致 Phalcon\Mvc\Model 将从数据库检索到的所有数据以一个数组的方式保存,因此在这样执行的地方会消耗更多的内存。

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

过滤结果集(Filtering Resultsets)

过滤数据最有效的方法是设置一些查询条件,数据库会利用表的索引快速返回数据。Phalcon 额外的允许你通过任何数据库不支持的方式过滤数据。

  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)

Phalcon\Mvc\Model 中也支持绑定参数。即使使用绑定参数对性能有一点很小的影响,还是强烈建议您使用这种方法,以消除代码受SQL注入攻击的可能性。 绑定参数支持字符串和整数占位符。实现方法如下:

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

如果是数字占位符,则必须把它们定义成整型(如1或者2)。若是定义为字符串型(如”1”或者”2”),则这个占位符不会被替换。

使用PDO_的方式会自动转义字符串。它依赖于字符集编码,因此建议在连接参数或者数据库配置中设置正确的字符集编码。 若是设置错误的字符集编码,在存储数据或检索数据时,可能会出现乱码。

另外你可以设置参数的“bindTypes”,这允许你根据数据类型来定义参数应该如何绑定:

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

默认的参数绑定类型是 Phalcon\Db\Column::BIND_PARAM_STR , 若所有字段都是string类型,则不用特意去设置参数的“bindTypes”.

如果你的绑定参数是array数组,那么数组索引必须从数字0开始:

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

参数绑定的方式适用于所有与查询相关的方法,如 find() , findFirst() 等等, 同时也适用于与计算相关的方法,如 count(), sum(), average() 等等.

若使用如下方式,phalcon也会自动为你进行参数绑定:

  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)

有时从数据库中获取了一条记录之后,在被应用程序使用之前,需要对数据进行初始化。 你可以在模型中实现”afterFetch”方法,在模型实例化之后会执行这个方法,并将数据分配给它:

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

如果使用getters/setters方法代替公共属性的取/赋值,你能在它被调用时,对成员属性进行初始化:

  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 “save” 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->save(
  5. [
  6. "type" => "mechanical",
  7. "name" => "Astro Boy",
  8. "year" => 1952,
  9. ]
  10. );

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->save($_POST);

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->save(
  5. $_POST,
  6. [
  7. "name",
  8. "type",
  9. ]
  10. );

创建与更新结果判断(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. }

These 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
DeletingbeforeDeleteYESRuns before the delete operation is made
DeletingafterDeleteNORuns after the delete operation was 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. }