Recent Posts
- (09/10) Fixing Warning: the ECDSA host key for 'github.com' differs from the key for the IP addressTAGS:Web Server Admin
- (12/26) CakePHP 3 - Getting List of Column Definitions from a Table (like schema())TAGS:CakephpCake3
- (09/14) Change Order of Loaded Behaviors in CakePHP 3TAGS:Cake3CakephpWeb ProgrammingPhp
- (05/29) CakePHP 3 - Accept JSON Header Only Working When Debug FalseTAGS:Web ProgrammingCakephpCake3
- (05/23) Remove All Events from Google Calendar (Reset Calendar)TAGS:Web ProgrammingPhp
- (11/08) Google Tag Manager (GTM) Not Firing Default PageView EventTAGS:Web ProgrammingJavascriptGoogle Tag Manager
- (10/13) In PHP, how do you get __toString() Magic Method Result without calling echo?TAGS:CakephpCake3Cakephp 13PhpWeb Programming
- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
Subscribe to my feed
MainelyDesign.com Blog
Change Order of Loaded Behaviors in CakePHP 3
Posted on 09/14/2018 at 09:33 am by Kevin Wentworth
Viewed 6,106 times | 0 comments
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
- $table->addBehavior('Aa');
- $table->addBehavior('Bb');
- // See which behaviors are loaded
- debug($table->behaviors()->loaded());
- // [Aa, Bb] are loaded
- // Now we'll drop and add Aa, which will put it at the end of the list
- $table->removeBehavior('Aa');
- $table->addBehavior('Aa');
- // See which behaviors are loaded
- debug($table->behaviors()->loaded());
- // [Bb, Aa] is the order of behaviors now ... uh oh! this will run Aa callbacks last
- // Instead, let's add Aa with a priority
- $table->removeBehavior('Aa');
- $table->addBehavior('Aa', ['priority' => 1]);
- // See which behaviors are loaded
- debug($table->behaviors()->loaded());
- // [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
Tags for Change Order of Loaded Behaviors in CakePHP 3
Cake3 | Cakephp | Web Programming | Php
Comments for this Posting
No comments. Be the first to post a reply.
Sorry, comments are closed for this posting.
Please Email Kevin if you have any questions. Thanks!