wordpress 插件中的类自动加载器 [英] Class autoloader in wordpress plugin
问题描述
我想编写一个类自动加载器以在 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.
推荐答案
使用一些像这样的实现.
Use some implementation like this one.
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的方式来做,只需在类中添加自动加载器功能.(即: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 插件中的类自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!