Tuesday, August 22, 2023

Change Order of Loaded Behaviors in CakePHP 3

 Turns out it's really easy to change the order of how behaviors are loaded in CakePHP 3.  Wait, I'm actually sort of lying.  You can't change the order of loaded behaviors. (BOO!).  In previous versions of Cake this was a problem... however, with the fully implemented Events subsystem in Cake3, all you need to do is change the priority of the behavior callbacks.  What's that, you say?

Change Order of Behaviors in Cake3

You actually don't need to worry about the order that behaviors are loaded anymore!  That's huge, because it completely decouples Behavior load order with callback order.  Let me show you:

Change the Order Programmatically

  1. $table->addBehavior('Aa');
  2. $table->addBehavior('Bb');
  3.  
  4. // See which behaviors are loaded
  5. debug($table->behaviors()->loaded());
  6.  
  7. // [Aa, Bb] are loaded
  8.  
  9. // Now we'll drop and add Aa, which will put it at the end of the list
  10. $table->removeBehavior('Aa');
  11. $table->addBehavior('Aa');
  12.  
  13. // See which behaviors are loaded
  14. debug($table->behaviors()->loaded());
  15.  
  16. // [Bb, Aa] is the order of behaviors now ... uh oh! this will run Aa callbacks last
  17.  
  18. // Instead, let's add Aa with a priority
  19. $table->removeBehavior('Aa');
  20. $table->addBehavior('Aa', ['priority' => 1]);
  21.  
  22. // See which behaviors are loaded
  23. debug($table->behaviors()->loaded());
  24.  
  25. // [Bb, Aa] is the order of behaviors still ... BUT the priority will fire Aa callbacks before Bb!!

Event Priority for Behavior Callback Order

By default, all behavior callbacks have a priority of 10.  Set the priority below 10 to run before everything else, or higher than 10 to run last.  Read the docs.

Cheers,
-Kevin Wentworth

No comments:

Post a Comment

Change Order of Loaded Behaviors in CakePHP 3

  Turns out it's really easy to change the order of how behaviors are loaded in CakePHP 3.  Wait, I'm actually sort of lying.  You c...