为了适应时间并改进我的编码实践,我开始实施namespaces 在我自己的插件中,由于有一些优势,such as eliminating ambiguity.
我找到了一个similar question 来帮助我建立我的插件模板,这对我很有用。然而,我后来对它做了一些修改。这是我的设置:
在里面wp-plugin-template/wp-plugin-template.php
:
<?php
/**
* Plugin Name: WP Plugin Template
*/
# If accessed directly, exit
if ( ! defined( \'ABSPATH\' ) ) exit;
# Call the autoloader
require_once( \'autoloader.php\' );
use PluginTemplate\\admin\\Plugin_Meta;
new Plugin_Meta;
在中wp-plugin-template/autoloader.php
:<?php
spl_autoload_register( \'autoload_function\' );
function autoload_function( $classname ) {
$class = str_replace( \'\\\\\', DIRECTORY_SEPARATOR, str_replace( \'_\', \'-\', strtolower($classname) ) );
# Create the actual file-path
$path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . \'.php\';
# Check if the file exists
if ( file_exists( $path ) ) {
# Require once on the file
require_once $path;
}
}
在中wp-plugin-template/admin/plugin-meta.php
:<?php
namespace PluginTemplate\\admin;
class Plugin_Meta {
public function __construct() {
add_action( \'plugins_loaded\', array($this, \'test\' ) );
}
public function test() {
echo \'It works!\';
}
}
当我尝试激活插件模板进行测试时,出现以下错误:Fatal error: 班PluginTemplate\\admin\\Plugin_Meta
在中找不到wp-content/plugins/wp-plugin-template/wp-plugin-template.php
在第11行
在这种情况下,第11行是:
new Plugin_Meta;
我想这是因为我将名称空间命名为PluginTemplate
? 我做错了什么?只是重申一下,the previous question that I mentioned 在我开始重命名文件和目录之前为我工作。