Eventy: WordPress-like Actions and Filters for Laravel
Published on by Paul Redmond
Eventy is a Laravel package by Tor Morten Jensen that brings WordPress-style actions and filters to your Laravel app.
This package has a lightweight API and makes it easy to build an action and filter system as found in WordPress. The action and filter system in WordPress is a powerful way to customize WordPress themes without modifying the template. For example, your users could easily tap into the <title></title>
tag (think wp_title
) to modify the way that title tags work without modifying the template.
Actions
Actions are code that you want to enable the ability to tap into code execution at a given point in your code.
Here’s the basic API for creating actions:
Eventy::action('my.hook', 'awesome');
The best place to add action listeners is in a service provider boot()
method:
public function boot(){ Eventy::addAction('my.hook', function($what) { echo 'You are '. $what; }, 20, 1);}
The Eventy::addAction()
method accepts the action name, the callback, the priority, and the number of expected args. The lower the priority number, the earlier the execution.
Filters
Like WordPress filters, the Eventy library provides a filter method to modify passed values. Every time a filter is called it returns it’s value after running through various callbacks:
$value = Eventy::filter('my.hook', 'awesome');
The first argument is the filter name, and the second is the value. If no filter listeners are attached, the return value would be awesome
.
The method siguature is the same as actions, including the priority and number of expected arguments:
Eventy::addFilter('my.hook', function($what) { $what = 'not '. $what; return $what;}, 20, 1); // returns `not awesome`
You can even combine actions and filters together:
Eventy::addAction('my.hook', function($what) { $what = Eventy::filter('my.hook', 'awesome'); echo 'You are '. $what;});
Templates
Using the same examples from the project’s readme, here’s what the template syntax looks like for this package:
{{-- for example, `echo "awesome"` --}}@action('my.hook', 'awesome') You are @filter('my.hook', 'awesome')
Learn More
You can learn more about Eventy from the project’s GitHub repository and install it with composer require tormjens/eventy
.