问题描述
我想编写一个可在wordpress插件中使用的类自动加载器.该插件将安装在多个站点上,我希望将与其他插件发生冲突的可能性降到最低.
I want to write a class autoloader to use in a wordpress plugin. This plugin will be installed on multiple sites, and i want to minimize the chance of conflicts with other plugins.
自动装带器将如下所示:
The autoloader will be something like this:
function __autoload($name) {
//some code here
}
我的主要问题是,如果另一个类也使用这样的函数会怎样?我认为这一定会带来问题.避免这种情况的最佳方法是什么?
My main issue is, what happens if another class also uses a function like this? I think it will be bound to give problems. What would be the best way to avoid something like that?
我试图不使用名称空间,因此该代码也可以在早期版本的php上使用.
I am trying to not use namespaces so the code will also work on previous versions of php.
推荐答案
使用这种实现方式.
function TR_Autoloader($className)
{
$assetList = array(
get_stylesheet_directory() . '/vendor/log4php/Logger.php',
// added to fix woocommerce wp_email class not found issue
WP_PLUGIN_DIR . '/woocommerce/includes/libraries/class-emogrifier.php'
// add more paths if needed.
);
// normalized classes first.
$path = get_stylesheet_directory() . '/classes/class-';
$fullPath = $path . $className . '.php';
if (file_exists($fullPath)) {
include_once $fullPath;
}
if (class_exists($className)) {
return;
} else { // read the rest of the asset locations.
foreach ($assetList as $currentAsset) {
if (is_dir($currentAsset)) {
foreach (new DirectoryIterator($currentAsset) as $currentFile)
{
if (!($currentFile->isDot() || ($currentFile->getExtension() <> "php")))
require_once $currentAsset . $currentFile->getFilename();
}
} elseif (is_file($currentAsset)) {
require_once $currentAsset;
}
}
}
}
spl_autoload_register('TR_Autoloader');
基本上,该自动装带器已注册,并具有以下功能:
Basically this autoloader is registered and has the following features:
- 您可以添加特定的类文件,如果不遵循特定的模式来查找包含您的类的文件的位置(assetList).
- 您可以将整个目录添加到您的班级搜索中.
- 如果已经定义了该类,则可以添加更多逻辑来处理它.
- 您可以在代码中使用条件类定义,然后在类加载器中覆盖您的类定义.
现在,如果您想以OOP方式进行操作,只需将autoloader函数添加到类中. (即:myAutoloaderClass),然后从构造函数中调用它.然后只需在您的functions.php中添加一行即可.
Now if you want want to do it in OOP way, just add the autoloader function inside a class. (ie: myAutoloaderClass) and call it from the constructor.then simply add one line inside your functions.php
new myAutoloaderClass();
并添加构造函数
function __construct{
spl_autoload_register('TR_Autoloader' , array($this,'TR_Autoloader'));
}
希望这会有所帮助.人力资源
Hope this helps.HR
这篇关于Wordpress插件中的类自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!