j10o/whenthen

WordPress 的 add_action 和 do_action(soon) 的封装插件

dev-main 2022-11-23 10:29 UTC

This package is auto-updated.

Last update: 2024-09-23 17:39:04 UTC


README

WhenThen

WordPress 的 add_action 和 do_action(soon) 的封装插件 :octocat:

简介

$wp_event = new \WhenThen\MiddleWare\Event();
$wp_event->when( $hook = array( 'name' => 'wp' ) )->then( function(){
    echo '𝙷𝚎𝚕𝚕𝚘, 𝚆𝚘𝚛𝚍𝙿𝚛𝚎𝚜𝚜';
});

基本用法

通过 composer

执行 composer require j10o/whenthen

或者定位到你的项目的 composer.json 文件,然后在 require 属性中添加 j10o/whenthen": "dev-main"

例如

{
    "require": {
        "j10o/whenthen": "dev-main"
    }
}

在你的插件的主文件中包含 vendor 自动加载。

// Require Composer's autoload file.
require __DIR__ . '/vendor/autoload.php';

// Create new event object.
$wp_event = new \WhenThen\MiddleWare\Event();

// Similar to add_action stuff with WordPress.
$wp_loaded = array(
    'name' => 'wp',
    'priority' => 10,
    'num_args' => 1
);

// Same here.
$footer_loaded = array(
    'name' => 'wp_footer',
    'priority' => 10,
);

// Closure function to call when something happen.
$do_this_thing_1 = function($query_vars) {
    error_log( var_export( $query_vars, true ) );
};

// Another closure function to call when something happen.
$do_this_thing_2 = function() {
    echo 'I am in footer.';
};

// Listen to the event.
$wp_event->when( $wp_loaded )->then( $do_this_thing_1 );

// Another one.
$wp_event->when( $footer_loaded )->then( $do_this_thing_2 );