Model Events


Events - 图1

Events and Events Manager

Models allow you to implement events that will be thrown while performing an insert/update/delete which can be used to define business rules. The following are the events supported by Phalcon\Mvc\Model and their order of execution:

OperationNameCan stop operation?Explanation
InsertingafterCreateNORuns after the required operation over the database system only when an inserting operation is being made
Inserting/UpdatingafterSaveNORuns after the required operation over the database system
UpdatingafterUpdateNORuns after the required operation over the database system only when an updating operation is being made
Inserting/UpdatingafterValidationYESIs executed after the fields are validated for not nulls/empty strings or foreign keys
InsertingafterValidationOnCreateYESIs executed after the fields are validated for not nulls/empty strings or foreign keys when an insertion operation is being made
UpdatingafterValidationOnUpdateYESIs executed after the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made
InsertingbeforeCreateYESRuns before the required operation over the database system only when an inserting operation is being made
Inserting/UpdatingbeforeSaveYESRuns before the required operation over the database system
UpdatingbeforeUpdateYESRuns before the required operation over the database system only when an updating operation is being made
Inserting/UpdatingbeforeValidationYESIs executed before the fields are validated for not nulls/empty strings or foreign keys
InsertingbeforeValidationOnCreateYESIs executed before the fields are validated for not nulls/empty strings or foreign keys when an insertion operation is being made
UpdatingbeforeValidationOnUpdateYESIs executed before the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made
Inserting/UpdatingonValidationFailsYES (already stopped)Is executed after an integrity validator fails
Inserting/UpdatingprepareSaveNOIs executed before saving and allows data manipulation
Inserting/UpdatingvalidationYESIs executed before the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made

Implementing Events in Models

The easier way to make a model react to events is to implement a method with the same name of the event in the model’s class:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function beforeValidationOnCreate()
  7. {
  8. echo 'This is executed before creating a Robot!';
  9. }
  10. }

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

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Products extends Model
  4. {
  5. public function beforeCreate()
  6. {
  7. // Set the creation date
  8. $this->created_at = date('Y-m-d H:i:s');
  9. }
  10. public function beforeUpdate()
  11. {
  12. // Set the modification date
  13. $this->modified_in = date('Y-m-d H:i:s');
  14. }
  15. }

Using a custom Events Manager

Additionally, this component is integrated with Phalcon\Events\Manager, this means we can create listeners that run when an event is triggered.

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Events\Event;
  5. use Phalcon\Events\Manager as EventsManager;
  6. class Robots extends Model
  7. {
  8. public function initialize()
  9. {
  10. $eventsManager = new EventsManager();
  11. // Attach an anonymous function as a listener for 'model' events
  12. $eventsManager->attach(
  13. 'model:beforeSave',
  14. function (Event $event, $robot) {
  15. if ($robot->name === 'Scooby Doo') {
  16. echo "Scooby Doo isn't a robot!";
  17. return false;
  18. }
  19. return true;
  20. }
  21. );
  22. // Attach the events manager to the event
  23. $this->setEventsManager($eventsManager);
  24. }
  25. }

In the example given above, the Events Manager only acts as a bridge between an object and a listener (the anonymous function). Events will be fired to the listener when robots are saved:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->name = 'Scooby Doo';
  5. $robot->year = 1969;
  6. $robot->save();

If we want all objects created in our application use the same EventsManager, then we need to assign it to the Models Manager:

  1. <?php
  2. use Phalcon\Events\Event;
  3. use Phalcon\Events\Manager as EventsManager;
  4. // Registering the modelsManager service
  5. $di->setShared(
  6. 'modelsManager',
  7. function () {
  8. $eventsManager = new EventsManager();
  9. // Attach an anonymous function as a listener for 'model' events
  10. $eventsManager->attach(
  11. 'model:beforeSave',
  12. function (Event $event, $model) {
  13. // Catch events produced by the Robots model
  14. if (get_class($model) === \Store\Toys\Robots::class) {
  15. if ($model->name === 'Scooby Doo') {
  16. echo "Scooby Doo isn't a robot!";
  17. return false;
  18. }
  19. }
  20. return true;
  21. }
  22. );
  23. // Setting a default EventsManager
  24. $modelsManager = new ModelsManager();
  25. $modelsManager->setEventsManager($eventsManager);
  26. return $modelsManager;
  27. }
  28. );

If a listener returns false that will stop the operation that is executing currently.

Logging Low-Level SQL Statements

When using high-level abstraction components such as Phalcon\Mvc\Model to access a database, it is difficult to understand which statements are finally sent to the database system. Phalcon\Mvc\Model is supported internally by Phalcon\Db. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer, thus allowing us to log SQL statements as they happen.

  1. <?php
  2. use Phalcon\Logger;
  3. use Phalcon\Events\Manager;
  4. use Phalcon\Logger\Adapter\File as FileLogger;
  5. use Phalcon\Db\Adapter\Pdo\Mysql as Connection;
  6. $di->set(
  7. 'db',
  8. function () {
  9. $eventsManager = new EventsManager();
  10. $logger = new FileLogger('app/logs/debug.log');
  11. // Listen all the database events
  12. $eventsManager->attach(
  13. 'db:beforeQuery',
  14. function ($event, $connection) use ($logger) {
  15. $logger->log(
  16. $connection->getSQLStatement(),
  17. Logger::INFO
  18. );
  19. }
  20. );
  21. $connection = new Connection(
  22. [
  23. 'host' => 'localhost',
  24. 'username' => 'root',
  25. 'password' => 'secret',
  26. 'dbname' => 'invo',
  27. ]
  28. );
  29. // Assign the eventsManager to the db adapter instance
  30. $connection->setEventsManager($eventsManager);
  31. return $connection;
  32. }
  33. );

As models access the default database connection, all SQL statements that are sent to the database system will be logged in the file:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = new Robots();
  4. $robot->name = 'Robby the Robot';
  5. $robot->created_at = '1956-07-21';
  6. if ($robot->save() === false) {
  7. echo 'Cannot save robot';
  8. }

As above, the file app/logs/db.log will contain something like this:

[Mon, 30 Apr 12 13:47:18 -0500][DEBUG][Resource Id #77] INSERT INTO robots(name, created_at) VALUES ('Robby the Robot', '1956-07-21')

Profiling SQL Statements

Thanks to Phalcon\Db, the underlying component of Phalcon\Mvc\Model, it’s possible to profile the SQL statements generated by the ORM in order to analyze the performance of database operations. With this you can diagnose performance problems and to discover bottlenecks.

  1. <?php
  2. use Phalcon\Db\Profiler as ProfilerDb;
  3. use Phalcon\Events\Manager as EventsManager;
  4. use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
  5. $di->set(
  6. 'profiler',
  7. function () {
  8. return new ProfilerDb();
  9. },
  10. true
  11. );
  12. $di->set(
  13. 'db',
  14. function () use ($di) {
  15. $eventsManager = new EventsManager();
  16. // Get a shared instance of the DbProfiler
  17. $profiler = $di->getProfiler();
  18. // Listen all the database events
  19. $eventsManager->attach(
  20. 'db',
  21. function ($event, $connection) use ($profiler) {
  22. if ($event->getType() === 'beforeQuery') {
  23. $profiler->startProfile(
  24. $connection->getSQLStatement()
  25. );
  26. }
  27. if ($event->getType() === 'afterQuery') {
  28. $profiler->stopProfile();
  29. }
  30. }
  31. );
  32. $connection = new MysqlPdo(
  33. [
  34. 'host' => 'localhost',
  35. 'username' => 'root',
  36. 'password' => 'secret',
  37. 'dbname' => 'invo',
  38. ]
  39. );
  40. // Assign the eventsManager to the db adapter instance
  41. $connection->setEventsManager($eventsManager);
  42. return $connection;
  43. }
  44. );

Profiling some queries:

  1. <?php
  2. use Store\Toys\Robots;
  3. // Send some SQL statements to the database
  4. Robots::find();
  5. Robots::find(
  6. [
  7. 'order' => 'name',
  8. ]
  9. );
  10. Robots::find(
  11. [
  12. 'limit' => 30,
  13. ]
  14. );
  15. // Get the generated profiles from the profiler
  16. $profiles = $di->get('profiler')->getProfiles();
  17. foreach ($profiles as $profile) {
  18. echo 'SQL Statement: ', $profile->getSQLStatement(), '\n';
  19. echo 'Start Time: ', $profile->getInitialTime(), '\n';
  20. echo 'Final Time: ', $profile->getFinalTime(), '\n';
  21. echo 'Total Elapsed Time: ', $profile->getTotalElapsedSeconds(), '\n';
  22. }

Each generated profile contains the duration in milliseconds that each instruction takes to complete as well as the generated SQL statement.