amphibee / hookable
一个面向对象的WordPress插件API包。
Requires
- php: ^7.4|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^9.0
- symfony/var-dumper: ^5.1
- vimeo/psalm: ^3.11
README
此包提供了一个面向对象的API,用于与WordPress 插件API一起使用。此包还包括自动“参数数量”计算和链式回调。
安装
您可以通过composer安装此包
composer require amphibee/hookable
用法
为每种类型的"hook"都提供了一个专门的类。
动作
要与动作交互,您需要使用\AmphiBee\Hooks\Action
类。
注册动作:
要注册一个动作,调用Action::add()
方法。此方法需要3个参数
use AmphiBee\Hooks\Action; Action::add($name, $callback, $priority);
您不需要提供回调函数的参数数量。这会自动使用反射API来解决。
链式回调:
您可以为在初始回调之后运行的额外回调提供支持。例如,您可能希望调用应用程序中的一个辅助程序以执行额外的操作。
use AmphiBee\Hooks\Action; Action::add('init', function () { // do something here... })->then([MyPlugin::class, 'checkUserIsAdmin']);
链式回调将接收初始回调的返回值以及初始回调接收的所有参数。
class MyPlugin { public static function checkUserIsAdmin($resultFromInitialCallback, ...$extraArgs) { // ... } }
运行动作:
您可以使用Action::do()
方法触发/运行一个动作,就像使用do_action
一样传递参数。
use AmphiBee\Hooks\Action; Action::do('my_plugin_action', $argument, $another);
移除动作:
要移除动作,请使用Action::remove()
方法
use AmphiBee\Hooks\Action; Action::remove('init', $callbackToRemove, $priority);
过滤器
要与过滤器交互,您需要使用\AmphiBee\Hooks\Filter
类。
注册过滤器:
要注册一个过滤器,请使用Filter::add()
方法
use AmphiBee\Hooks\Filter; Filter::add('the_title', function ($title) { return $title . ' is the title.'; });
链式回调:
您可以为在初始回调之后运行的额外回调提供支持。例如,您可能希望调用应用程序中的一个辅助程序以执行额外的操作。
use AmphiBee\Hooks\Filter; Filter::add('the_title', function ($title) { return $title . ' is the title.'; })->then('strtoupper');
链式回调的行为将与动作相同,并将接收初始回调的返回值以及传递给初始回调的任何参数。
上面的示例将把$title . ' is the title'
的返回值传递给strtoupper
方法。
应用过滤器:
您可以使用Filter::do()
或Filter::apply()
方法(Filter::apply()
是Filter::do()
的别名)应用过滤器。这些方法的行为与Action::do()
方法相同,并接受相同的参数。
use AmphiBee\Hooks\Filter; $title = Filter::do('the_title', 'Hello, World!'); // or.. $title = Filter::apply('the_title', 'Hello, World!');
移除过滤器:
您可以使用Filter::remove()
方法移除过滤器。这与Action::remove()
方法的行为相同,并且两者都使用相同的底层逻辑。
$callback = function () { }; // logic here... Filter::remove('the_title', $callback);
可钩接的类
此包提供了一个方便的Hookable
接口,可用于注册单次使用的类回调。
use AmphiBee\Hooks\Contracts\Hookable; class InitAction implements Hookable { public function execute() { // ... } } Action::add('init', InitAction::class);
接收钩子参数:
要接收调用者传递的参数,在您的类中定义一个构造函数并将它们分配给属性
use AmphiBee\Hooks\Contracts\Hookable; class TheTitleFilter implements Hookable { private string $title; public function __construct(string $title) { $this->title = $title; } public function execute() { if ($this->title !== 'My First Post') { return $this->title; } return "{$this->title} is Amazing!"; } } Filter::add('the_title', TheTitleFilter::class);
测试
composer test
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
贡献
有关详细信息,请参阅CONTRIBUTING。
安全
如果您发现任何安全问题,请通过电子邮件ryan@digitalbit.dev而不是使用问题跟踪器。
致谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。