madeinitalyslc / mit-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-09-12 23:31:52 UTC
README
为您的WordPress插件添加一些结构。
需要PHP 7.1+。
安装
要在项目中使用此库,请将其添加到 composer.json
composer require madeinitalyslc/mit-wp-plugin
创建插件
插件是一个简单的对象,用于帮助启动功能,通过允许您轻松检索插件信息、引用内部文件和URL以及注册钩子。
<?php /** * Plugin Name: Stucture */ use MadeInItalySLC\WP\Plugin\PluginFactory; if (file_exists( __DIR__.'/vendor/autoload.php')) { require_once __DIR__.'/vendor/autoload.php'; } function StucturePlugin() { static $stucture_wp_plugin; if (!$stucture_wp_plugin) { $stucture_wp_plugin = PluginFactory::create('stucture-wp-plugin'); } return $stucture_wp_plugin; } $stucture = StucturePlugin();
$stucture
是 Plugin
的实例,并实现了 PluginInterface
,它提供了一组基本的API来访问有关插件的信息。
钩子提供者
相关的功能可以封装在一个称为“钩子提供者”的类中,当启动插件时进行注册。
钩子提供者允许您封装相关的功能,维护状态而不使用全局变量,不使用前缀命名空间方法,限制对内部方法的访问,并使单元测试更容易。
例如,MadeInItalySLC\WP\Plugin\Provider\I18n
类是一个默认的钩子提供者,它可以自动加载文本域,以便插件可以进行翻译。
钩子提供者的唯一要求是它应该通过定义一个名为 registerHooks()
的方法来实现 HookProviderInterface
。
通过调用 Plugin::registerHooks()
来注册钩子提供者,如下所示
<?php $stucture ->registerHooks(new \MadeInItalySLC\WP\Plugin\Provider\I18n()) ->registerHooks(new \MadeInItalySLC\WP\Plugin\Provider\VarDumpServer()) ->registerHooks(new \Structure\PostType\BookPostType());
提供者 BookPostType
可能看起来像这样
<?php namespace Structure\PostType; class BookPostType extends AbstractHookProvider { const POST_TYPE = 'book'; public function registerHooks() { $this->addAction('init', 'registerPostType'); $this->addAction('init', 'registerMeta'); } protected function registerPostType() { register_post_type(static::POST_TYPE, $this->getArgs()); } protected function registerMeta() { register_meta('post', 'isbn', [ 'type' => 'string', 'single' => true, 'sanitize_callback' => 'sanitize_text_field', 'show_in_rest' => true, ]); } protected function getArgs() { return [ '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
钩子提供者中,回调是类的受保护方法。
使用 HooksTrait
可以像那样锁定API,这是由John P. Bloch开发的 。
插件意识
钩子提供者可以实现 PluginAwareInterface
,以便在注册钩子时自动接收对插件的引用。
例如,在这个类中,enqueueAssets()
方法引用内部 $plugin
属性以检索插件中的JavaScript文件的URL。
<?php namespace Structure\Provider; use MadeInItalySLC\WP\Plugin\AbstractHookProvider; class Assets extends AbstractHookProvider { public function registerHooks() { $this->addAction('wp_enqueue_scripts', 'enqueueAssets'); } protected function enqueueAssets() { wp_enqueue_script( 'structure', $this->getPlugin()->getUrl('assets/js/structure.js') ); } }
另一个例子是前面提到的 I18n
提供者。它接收对插件对象的引用,以便可以使用插件的基本名称和短名称来加载文本域。
扩展 AbstractHookProvider
的类自动“有插件意识”。
许可
版权(c)2017 Cedaro,LLC 版权(c)2019 Made In Italy SLC
本库采用MIT许可。
感谢归属,但不是必需的。