creativesofttechsolutions / laravelhooks
Wordpress Like Hooks System Package For Laravel
v1.0.1
2025-06-14 15:37 UTC
Requires
- php: ^8.2
- laravel/framework: ^10.0|^11.0|^12.0
README
This documentation explains how to build and use a flexible and performant hook system in Laravel 12. It supports both actions and filters, similar to WordPress, and works across controllers, Livewire components, middleware, and modules.
๐ Installation
To install the creativesofttechsolutions/laravelhooks
package, use Composer:
composer require creativesofttechsolutions/laravelhooks
๐ง What Are Actions and Filters?
๐น Actions
- Actions are event triggers.
- They allow you to run additional code when something happens (e.g., after user registration, after an order is placed).
- Actions do not modify any data โ they just perform side effects.
hooks()->addAction('after_user_register', function ($user) { Log::info("New user: " . $user->email); });
๐ธ Filters
- Filters are used to modify and return data.
- They allow other parts of the application or plugins to intercept, change, or validate values before they are used.
hooks()->addFilter('post_title', function ($title) { return strtoupper($title); });
๐ Usage Examples
Triggering an action:
hooks()->doAction('after_user_register', $user);
Adding an action (e.g., in a module):
hooks()->addAction('after_user_register', function ($user) { Log::info("User Registered: " . $user->email); });
Adding and using filters:
hooks()->addFilter('product_price', function ($price, $product) { return $product->discount ? $price * 0.9 : $price; }); $price = hooks()->applyFilters('product_price', $originalPrice, $product);
๐ฆ Where to Define Hooks in Modules
In Modules/YourModule/Providers/ModuleServiceProvider.php
:
public function boot(): void { hooks()->addAction('after_user_register', ...); hooks()->addFilter('modify_data', ...); }
Or in a dedicated class like:
Modules/YourModule/Hooks/HookRegistrar.php
And load them like:
HookRegistrar::register();
โ๏ธ Using Hooks in Controllers, Livewire, Middleware
In Controllers:
hooks()->doAction('after_order_created', $order);
In Livewire Components:
$this->value = hooks()->applyFilters('modify_value', $this->value);
In Middleware:
$request = hooks()->applyFilters('modify_request', $request);
โ Best Practices
- Use meaningful, unique hook names.
- Actions for side effects, Filters for modifying data.
- Use classes instead of closures for better readability and testing.
- Avoid heavy operations inside hook callbacks.
This system brings WordPress-style flexibility to Laravel while preserving Laravelโs clean architecture. You can dynamically extend your app and let plugins interact with core logic cleanly.