ahmetertem/hook

Laravel的简单钩子引擎

dev-master 2023-06-09 21:35 UTC

This package is auto-updated.

Last update: 2024-09-10 00:14:25 UTC


README

命名空间更改了吗?

我不得不将命名空间从Esemve改为我的,因为在这种情况下,我无法从Illuminate的反射器中加载它。原始作者是Esembe。

这是什么?

本项目旨在使您的包能够相互修改,而不必覆盖源代码。

什么是钩子?

它类似于一个事件。除非钩子监听器捕获它并命令运行钩子中的其他函数,否则绑定在钩子上的代码会运行。它们可以按顺序设置,因此您可以在代码中进行多次修改。

它有什么好处?

示例1:您有一个模块,显示一个编辑器。在每个情况下,编辑器都保持不变。如果您将编辑器的显示绑定在钩子上,那么您可以编写一个模块来重新定义/覆盖这个钩子,例如将textarea更改为ckeditor。

示例2:您列出用户。您可以在钩子中包含每行的打印。这样,您可以编写一个独立的模块,可以扩展此行以打印电子邮件地址。

示例3:您将用户数据保存到数据库中。如果您在钩子中这样做,您可以编写一个模块,可以为用户模型添加额外字段,如"first name"或"last name"。为此,您不需要修改处理用户的代码,扩展模块不需要知道主模块的功能。

...还有许多其他事情。如果您正在构建一个类似于CMS的系统,这将使您的生活变得更加容易。

我如何安装它?

composer require ahmetertem/hook

然后到app.php

...
'providers' => [
    ...
    AhmetErtem\Hook\HookServiceProvider::class,
    ...
 ],
 'aliases' =>[
    ...
    'Hook' => AhmetErtem\Hook\Facades\Hook::class
    ...
 ]

它是如何工作的?

示例

$user = new User();
$user = Hook::get('fillUser',[$user],function($user){
    return $user;
});

在这种情况下,抛出了一个fillUser钩子,它接收$user对象作为参数。如果没有东西捕获它,内部函数将返回$user,所以不会发生任何事情。但它可以被提供者的监听器捕获

Hook::listen('fillUser', function ($callback, $output, $user) {
    if (empty($output))
    {
      $output = $user;
    }
    $output->profilImage = ProfilImage::getForUser($user->id);
    return $output;
}, 10);

$callback包含钩子的原始内部函数,因此可以在这里调用它。

可以为钩子注册多个监听器,因此监听器在$输出中接收先前注册的钩子监听器的响应。

然后是钩子传递的参数,在这种情况下是用户。

上面的钩子监听器捕获了fillUser的调用,扩展了接收到的对象,并将其返回到原来的位置。钩子运行后,$user对象包含了一个profilImage变量。

示例中的数字10是优先级。它们按顺序执行,因此如果为fillUser注册了数字5,它将在数字10之前运行。

初始输出

您也可以将初始输出传递给监听器。

$initialOutput='test string';

\Hook::get('testing',['other string'],function($otherString){
    return $otherString;
},$initialOutput)

// and later ...

Hook::listen('testing', function ($callback, $output, $otherString) {
    if ($output==='test string') {
        $output="{$output} yeeeaaaayyy!";
    }
    if ($otherString==='other_string') {
        // other string is good too
    }
    return $output; // 'test string yeeeaaaayyy!'
});

如果没有监听器,将返回'other string'。

在blade模板中使用

@hook('hookName')

在这种情况下,钩子监听器可以像这样捕获它

 Hook::listen('template.hookName', function ($callback, $output, $variables) {
   return view('test.button');
 });

在$variables变量中,它接收所有可用于blade模板的变量。

要监听blade模板,您需要监听template.hookName而不是只是hookName

包装HTML

@hook('hookName', true)
    this content can be modified with dom parsers
    you can inject some html here
@endhook

现在,$output参数包含由钩子组件包装的HTML。

Hook::listen('template.hookName', function ($callback, $output, $variables) {
  return "<div class=\"alert alert-success\">$output</div>";
});

停止

Hook::stop();

将停止放在钩子监听器中停止注册到该钩子的其他监听器的运行。

用于测试

Hook::mock('hookName','returnValue');

之后,hookName钩子将返回returnValue作为响应。

Artisan

php artisan hook::list

列出所有活动的钩子监听器。

许可协议:MIT