Wordpress Like Hooks System Package For Laravel

v1.0.1 2025-06-14 15:37 UTC

This package is auto-updated.

Last update: 2025-06-14 16:26:07 UTC


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.