cedaro / wp-plugin
WordPress插件的基础库。
Requires
- php: >=5.4.0
- psr/container: ^1.0
Requires (Dev)
- phpunit/phpunit: *@stable
This package is auto-updated.
Last update: 2024-08-29 04:39:27 UTC
README
为您的WordPress插件添加一些结构。
需要PHP 5.4+。
安装
要在项目中使用此库,请将其添加到 composer.json
composer require cedaro/wp-plugin
创建插件
插件是一个简单的对象,用于通过允许您轻松检索插件信息、引用内部文件和URL以及注册钩子来帮助启动功能。
<?php /** * Plugin Name: Structure */ use Cedaro\WP\Plugin\PluginFactory; if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) { require( __DIR__ . '/vendor/autoload.php' ); } $structure = PluginFactory::create( 'structure' );
$stucture
是 Plugin
的实例,并实现了 PluginInterface
,它提供了一个基本的API来访问有关插件的信息。
钩子提供者
相关的功能可以封装在一个名为“钩子提供者”的类中,在启动插件时进行注册。
钩子提供者允许您封装相关的功能,在不使用全局变量的情况下维护状态,无需前缀函数地命名空间方法,限制对内部方法的访问,并使单元测试更容易。
例如,Cedaro\WP\Plugin\Provider\I18n
类是一个默认的钩子提供者,它可以自动加载文本域,以便插件可以进行翻译。
钩子提供者的唯一要求是应该通过定义一个名为 register_hooks()
的方法来实现 HookProviderInterface
。
通过调用 Plugin::register_hooks()
如此注册钩子提供者
<?php $structure ->register_hooks( new \Cedaro\WP\Plugin\Provider\I18n() ) ->register_hooks( new \Structure\PostType\BookPostType() );
例如,BookPostType
提供者可能看起来像这样
<?php namespace Structure\PostType; use Cedaro\WP\Plugin\AbstractHookProvider; class BookPostType extends AbstractHookProvider { const POST_TYPE = 'book'; public function register_hooks() { $this->add_action( 'init', 'register_post_type' ); $this->add_action( 'init', 'register_meta' ); } protected function register_post_type() { register_post_type( static::POST_TYPE, $this->get_args() ); } protected function register_meta() { register_meta( 'post', 'isbn', array( 'type' => 'string', 'single' => true, 'sanitize_callback' => 'sanitize_text_field', 'show_in_rest' => true, ) ); } protected function get_args() { return array( 'hierarchical' => false, 'public' => true, 'rest_base' => 'books', 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => false, 'show_in_rest' => true, ); } }
受保护的钩子回调
在WordPress中,只能使用类的公共方法作为钩子回调,但在上述 BookPostType
钩子提供者中,回调是类的受保护方法。
可以通过使用由John P. Bloch开发的 HooksTrait
来锁定API,如上所述。
插件感知
钩子提供者可以通过实现 PluginAwareInterface
在其钩子注册时自动接收对插件的引用。
例如,在此类中,enqueue_assets()
方法引用内部的 $plugin
属性以检索插件中JavaScript文件的URL。
<?php namespace Structure\Provider; use Cedaro\WP\Plugin\AbstractHookProvider; class Assets extends AbstractHookProvider { public function register_hooks() { $this->add_action( 'wp_enqueue_scripts', 'enqueue_assets' ); } protected function enqueue_assets() { wp_enqueue_script( 'structure', $this->plugin->get_url( 'assets/js/structure.js' ) ); } }
另一个例子是前面提到的 I18n
提供者。它接收对插件对象的引用,以便可以使用插件的基本名称和短名来加载文本域。
扩展 AbstractHookProvider
的类自动“感知插件”。
许可证
版权(c)2017 Cedaro, LLC
此库根据MIT许可证授权。
感谢归属,但不是必需的。