theanh / laravel-hooks

该软件包已被放弃,不再维护。作者建议使用 tadcms/hooks 软件包。

在 Laravel 中添加动作和过滤器,就像 WordPress 一样。

v1.0.4 2021-05-08 07:00 UTC

This package is auto-updated.

Last update: 2021-08-11 11:52:48 UTC


README

在 Laravel 中添加动作和过滤器,就像 WordPress 一样。

安装

  • 使用 Composer 安装
composer require tadcms/hooks

如果您使用的是 Laravel 5.5 或更高版本,您可以从现在开始使用此软件包。Eventy 将由 Laravel 框架自动发现。

  • 对于 Laravel < 5.5,请将服务提供者添加到您的 config/app.php 文件中的 providers 数组中。
'Tadcms\Hooks\HooksServiceProvider',

使用方法

在代码的任何位置,您都可以创建一个新的动作,如下所示

do_action($tag, ...$args)
 * TAD CMS: Do action hook
 * @param string $tag Action / Hook name (E.x: my.hook)
 * @param mixed ...$args Additional parameters to pass to the callback functions.
 * @return void

添加动作 为了监听您的钩子,您需要附加监听器。最好将这些监听器添加到您的 AppServiceProvider boot() 方法中。

add_action($tag, $callback, $priority = 20, $arguments = 1)
 * Add action to hook
 * @param string $tag The name of the filter to hook the $function_to_add callback to.
 * @param callable $callback The callback to be run when the filter is applied.
 * @param int $priority Optional. Used to specify the order in which the functions
 *                                  associated with a particular action are executed.
 *                                  Lower numbers correspond with earlier execution,
 *                                  and functions with the same priority are executed
 *                                  in the order in which they were added to the action. Default 20.
 * @param int $arguments Optional. The number of arguments the function accepts. Default 1.
 * @return void

应用过滤器

apply_filters($tag, $value, ...$args)
 * TAD CMS: Apply filters to value
 * @param string $tag The name of the filter hook.
 * @param mixed  $value The value to filter.
 * @param mixed  ...$args Additional parameters to pass to the callback functions.
 * @return mixed The filtered value after all hooked functions are applied to it.

添加过滤器 为了监听您的钩子,您需要附加监听器。最好将这些监听器添加到您的 AppServiceProvider boot() 方法中。

add_filters($tag, $callback, $priority = 20, $arguments = 1)
  * @param string $tag The name of the filter to hook the $function_to_add callback to.
  * @param callable $callback The callback to be run when the filter is applied.
  * @param int $priority Optional. Used to specify the order in which the functions
  *                                  associated with a particular action are executed.
  *                                  Lower numbers correspond with earlier execution,
  *                                  and functions with the same priority are executed
  *                                  in the order in which they were added to the action. Default 20.
  * @param int $arguments   Optional. The number of arguments the function accepts. Default 1.
  * @return bool

在 Blade 中使用

添加与上述动作示例相同的动作

@do_action('my.hook', $user)

添加与上述过滤器示例相同的过滤器

You are @apply_filters('my.hook', 'awesome')