razu/laravel-hooks
Composer 安装命令:
composer require razu/laravel-hooks
包简介
The filter and action system in Laravel is inspired by Wordpress hooks
README 文档
README
The filter and action system in Laravel is inspired by WordPress hooks
About
Actions are code snippets that run at specific points in your program. They don't return any value but provide a way to hook into your existing code without causing interference.
Filters are designed to alter data. They always return a value, typically the modified version of the first parameter, which is the default return behavior.
Notes: This works similarly to the Observer design pattern, or the Publisher/Subscriber pattern, which is also related to event-driven architecture.
More Resources
Read more about filters and actions
Installation
- Install using Composer
composer require razu/laravel-hooks
Great! Now you're ready to use laravel-hooks.
ACTION
EVENT
do_action( string $tag, mixed $arg )
The do_action function is used to trigger all callback functions attached to a specified action hook ($tag).
Parameters
-
$tag(string) (Required) – The name of the action hook that will be triggered. This specifies the point in the code where the action occurs. -
$arg(mixed) (Optional) – Additional arguments that can be passed to the functions hooked to this action. Defaults to empty if not provided.
LISTENER
add_action( string $tag, callable $callback, int $priority = 10, int $accepted_args = 1 )
The add_action function associates a callback function with a specified hook ($tag) in a Laravel or WordPress-style hook system. Here’s what each parameter does:
Parameters
-
$tag(string) (Required) The name of the hook to which the callback function should be attached. -
$callback(callable) (Required) The function to be executed when the hook is triggered. -
$priority(int) (Optional) Determines the order in which the functions associated with a particular hook are executed. Lower numbers correspond to earlier execution. Default value: 10 -
$accepted_args(int) (Optional) The number of arguments the callback function accepts. Default value: 1
By using add_action, you can ensure that your custom functions are executed at the appropriate points in your application’s lifecycle, allowing you to extend or modify functionality as needed.
FILTER
EVENT
apply_filters( string $tag, mixed $value )
The apply_filters function calls all functions attached to a specific filter hook ($tag). This allows you to modify a value by passing it through multiple filters.
Parameters
$tag(string) (Required) – The name of the filter hook to trigger. This identifies the specific filter to apply.$value(mixed) (Required) – The value to be filtered. Each function attached to the hook can modify and return this value.
When apply_filters is called, it sequentially runs all functions associated with hook ($tag), passing $value through each one. This allows custom modifications to be made to the value at specific points in the application.
LISTENER
add_filter( string $tag, callable $callback, int $priority = 10, int $accepted_args = 1 )
The add_filter function allows you to modify various types of internal data at runtime by attaching callback functions to specific filter hooks.
Parameters
-$tag
(string) (Required) – The name of the filter to which the callback will be added. This specifies the specific filter hook where data modification should occur.
-$callback
(callable) (Required) – The callback function to be executed when the filter is applied. This function should process and potentially modify the filtered data.
-$priority
(int) (Optional) – Specifies the order in which functions associated with this filter will execute. Lower numbers correspond to earlier execution. Functions with the same priority are executed in the order they were added. The default is 10.
$accepted_args(int) (Optional) – The number of arguments the callback function accepts. The default is 1.
Using add_filter, you can ensure that specific functions modify data when the designated filter is applied, allowing for flexible data processing throughout the application.
Here’s how to pass a callback function:
The callback can be specified in various ways, including:
- An anonymous function.
- A string referring to a class and method within the application, like
OurNamespace\Http\Listener\ourClass@ourHookListenerMethod. - An array format, such as
[$object, 'method']. - A globally defined function, such as
global_function.
Examples
- Using an anonymous function:
add_action('user_registered', function($user) { $user->sendEmailVerificationCode(); }, 20, 1);
- Using a class method reference as a string:
add_action('user_registered', 'OurNamespace\Http\Listener\ourClass@ourHookListenerMethod', 20, 1); add_action('user_registered', 'OurNamespace\Http\Controllers\ourController@ourMethodName', 20, 1);
- Using an array callback:
add_action('user_registered', [$object, 'ourMethod'], 20, 1);
Usages
Actions
Anywhere in your code, you can define a new action like this:
do_action('user_registered', $user);
Here, user_registered is the action name, which will be used later when the action is being listened to.
The $user parameter will be available whenever you listen for the action. This parameter can represent any relevant data.
To listen for your actions, attach listeners at the appropriate points. Another good approach is to add these in the boot() method of your AppServiceProvider.
For example, if you want to hook into the above action, you could do the following:
add_action('user_registered', function($user) { $user->sendEmailVerificationCode(); }, 10, 1);
The first argument must be the name of the action. The second argument can be closures, callbacks, or anonymous functions. The third argument specifies the order in which the functions associated with a particular action are executed. Lower numbers correspond to earlier execution, and functions with the same priority are executed in the order in which they were added to the action. The default value is 10. The fourth argument specifies the number of arguments the function accepts, with the default value being 1.
Filters
Filters must always have data coming in and going out to ensure it reaches the browser for output. Your content might pass through multiple filters before finally being displayed. In contrast, actions—though similar to filters—do not require any data to be returned. However, data can still be passed through actions if needed.
Filters are functions in Laravel applications that allow data to be passed through and modified. They enable developers to adjust the default behavior of specific functions.
Here’s an example of how a filter can be used in a application.
In the Product.php model, we have a getAvailable method that builds a query to fetch all available products:
class Product extends Model { public function getAvailable() { return Product::where('available_at', '<=', now()); } }
Using a filter, we can modify this query dynamically:
class Product extends Model { public function getAvailable() { return apply_filters('products_available', Product::where('available_at', '<=', now())); } }
Now, in the entry point of the application, such as in a module or plugin, you can modify this product availability query.
In the service provider of the module or plugin (ideally within the boot method), we'll register a listener for the filter.
class ModuleServiceProvider extends ServiceProvider { public function boot() { // Registering a filter to modify the query for available products add_filter('products_available', function($query) { return $query->where('status', 'active'); }); } }
License
This software is licensed under the (MIT) License. For more details, please refer to the License file.
Related Link
razu/laravel-hooks 适用场景与选型建议
razu/laravel-hooks 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 14 次下载、GitHub Stars 达 3, 最近一次更新时间为 2024 年 11 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「event」 「wordpress」 「events」 「filter」 「HOOK」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 razu/laravel-hooks 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 razu/laravel-hooks 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 razu/laravel-hooks 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Библиотека для реализаций паттерна Pub/Sub
Wireless Cross-Component Communication
A powerful event calendar Tool for Laravel's Nova 5.
Symfony bundle for broadway/broadway.
Command bus implementation: Commands and domain events
This is an Event Emitter equivalent to Node.js' Event Emitter.
统计信息
- 总下载量: 14
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 4
- 点击次数: 10
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-11-08