shohel/pluggable

添加动作/过滤器钩子以使您的 Laravel | Codeigniter | PHP 项目可扩展

1.0.0 2020-05-31 17:25 UTC

This package is not auto-updated.

Last update: 2024-09-17 12:44:11 UTC


README

如果您喜欢这个库,请在这个仓库和我的个人资料上放置星标 ⭐。

可插拔

使用 Pluggable,您可以将动作钩子、过滤器钩子注册到您的 PHP 项目中,如 WordPress,无论它是一个原始 PHP 项目、Laravel、Codeigniter、Moodle LMS 或其他。这是一个使您的 PHP 项目变得可扩展的库。

安装

使用 [Composer] 安装此包

$ composer require shohel/pluggable

Laravel 集成

Pluggable 对 Laravel 有很好的支持,并附带 Service Provider 以便于集成。Laravel 会包含 vendor/autoload.php,因此您无需手动 require 或自动加载。只需查看下面的说明。

安装 Pluggable 后,打开您的 Laravel 配置文件 config/app.php 并添加以下行。

在 $providers 数组中,将此包的 Service Providers 作为第一个条目添加。

\Shohel\Pluggable\PluggableServiceProvider::class,

现在 Pluggable 将被 Laravel 自动加载。

其他 PHP 项目的集成

在引导/入口点之前将 composer 自动加载文件包含到您的项目中。

// include composer autoload
require 'vendor/autoload.php';

// import the Pluggable HookManager Class
use Shohel\Pluggable\HookManager;

// create a hook manager instance, composer will do rest
$hookManager = new HookManager();

Pluggable 会完成其余工作。

用法

动作钩子

do_action( string $tag, mixed $arg )

执行特定动作钩子上挂载的函数。

此函数调用附加到动作钩子 $tag 的所有函数。通过使用 $tag 参数指定新钩子的名称,可以简单地调用此函数来创建新的动作钩子。

示例用法

// The action callback function.
function example_callback( $arg1, $arg2 ) {
    // (maybe) do something with the args.
}
add_action( 'example_action', 'example_callback', 10, 2 );

/*
 * Trigger the actions by calling the 'example_callback()' function
 * that's hooked onto `example_action` above.
 *
 * - 'example_action' is the action hook.
 * - $arg1 and $arg2 are the additional arguments passed to the callback.
$value = do_action( 'example_action', $arg1, $arg2 );

过滤器钩子

apply_filters( string $tag, mixed $value )

调用已添加到过滤器钩子的回调函数。

通过调用此函数并使用 $tag 参数指定新钩子的名称,可以调用附加到过滤器钩子的回调函数。此函数可用于通过简单地使用 $tag 参数指定新钩子的名称来创建新的过滤器钩子。

示例用法

// The filter callback function.
function example_callback( $string, $arg1, $arg2 ) {
    // (maybe) modify $string.
    return $string;
}
add_filter( 'example_filter', 'example_callback', 10, 3 );

/*
 * Apply the filters by calling the 'example_callback()' function
 * that's hooked onto `example_filter` above.
 *
 * - 'example_filter' is the filter hook.
 * - 'filter me' is the value being filtered.
 * - $arg1 and $arg2 are the additional arguments passed to the callback.
$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );

从类中调用钩子回调

您可以使用 ['className','callbackMethod'] 或在类中使用它来引用类方法作为钩子回调,而不是函数。 [$this,'getStuffDone']

这是一个更好的方法

class MyClass {
     function __construct() {
          add_action( 'example_action',array( $this, 'callbackMethod' ) );
     }
     function callbackMethod() {
          // .. This is where stuff gets done ..
     }
}
$var = new MyClass();

由于钩子将像 WordPress 一样工作,您可以在 WordPress.org 文档中了解更多关于动作钩子/过滤器钩子的信息。

动作钩子 | 过滤器钩子

如果您喜欢这个库,请在这个仓库和我的个人资料上放置星标 ⭐。