简单来说,我正在尝试使用WordPress构建一个“生态系统”,其中包括一个核心插件和其他附加插件。
更深入地说,每个附加插件都需要核心插件才能正常运行。我已经使用WordPress标准编码和文件结构实践来实现这一点。现在,我正在重新设计这个项目,使用命名空间PSR-4、composer、bower等工具。
标准WordPress安装
|
|__www
|
|___wp-admin
|
|___wp-content
| |
| |___plugins
| | |
| | |___my-core-plugin
| | | |
| | | |___library
| | | | |
| | | | |___class-post-register.php
| | | |
| | | |___vendor
| | | | |
| | | | |___autoload.php
| | | |
| | | |___composer.json
| | | |
| | | |___core.php
| | |
| | |___my-first-addon-plugin
| | | |
| | | |___library
| | | |
| | | |___vendor
| | | | |
| | | | |___autoload.php
| | | |
| | | |___composer.json
| | | |
| | | |___core.php
| | |
| | |___my-second-addon-plugin
| | | |
| | | |___library
| | | |
| | | |___vendor
| | | | |
| | | | |___autoload.php
| | | |
| | | |___composer.json
| | | |
| | | |___core.php
| | |
| |___themes
| | |
| | |___my-custom-theme
| |
| wp-includes
通过composer使用核心插件psr4
"autoload": {
"psr-4": {
"CorePlugin\\Library\\": "library"
}
}
示例核心插件类
<?php
namespace CorePlugin\library;
class Post_Register {
private __construct() {
// ... code
}
private init() {
}
private register( $data ) {
// .. code to register a custom post for example.
}
}
首先通过composer添加psr4插件
"autoload": {
"psr-4": {
"FirstAddon\\Library\\": "library"
}
}
来自插件的类
以下是我困惑的地方。我尝试在不同的命名空间中使用核心插件中的一个类,结果出现了以下错误:
致命错误:未找到“CorePlugin\Library\Post_Register”类...
这两个插件都自动加载其各自生成的Composer自动加载文件,因此我认为我应该能够使用命名空间。在深入研究PHP手册的这一部分之前,我来这里询问一下 (http://php.net/manual/en/language.namespaces.php) ,也许我会尝试子命名空间。
<?php
namespace FirstAddon;
use CorePlugin\Library\Post_Register;
class First_Addon {
private __construct() {
// ... code
}
private init() {
}
private another_function() {
}
}
此外,我不确定是否应该使用带括号的子命名空间,例如在 Laravel 中:
use
foo\bar; 和 use
bar\foo;。<?php namespace App\Services;
use App\User;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
class Registrar implements RegistrarContract {