我正在尝试创建一个load plugin(plugin)函数,该函数将从plugin文件夹获取php文件,并将其变量/函数加载到站点中。
问题是我们都知道职能不是全球性的,这就引出了我的问题。
由于可以包含任何文件,因此我无法将文件中的每个变量设置为全局变量,因为它们可以是随机的和无限的,我希望将其设置为这样,文件中的任何函数都可以在页面上的任何位置使用。
任何关于如何做到这一点的建议都是很好的。谢谢!
这就是我目前所拥有的:
function loadPlugin($name,$debug='') {
if(file_exists("scripts/plugins/".$name)) {
include("scripts/plugins/".$name);
} else if(strtolower($debug)=='d') trigger_error($name." does not exists in the plugins folder.", E_USER_ERROR);
}
最佳答案
嗯,我也遇到了类似的问题,决定去寻找一些可重用和可扩展的东西。
所以,我帮你整理一下,只是为了演示科林的答案。代码可以改进:)
<?php
/**
* Autoloader
* @Usage:
* // set autoload paths
* Loader::setPaths(
* array("interface_path"=>dirname(__FILE__). "/core"),
* array("plugin_path"=>"/var/www/awesome-app/plugins"),
* array("controller_path"=>dirname(__FILE__). "/controllers")
* );
*
*
* // Now, the magic
* Loader::registerAutoloads();
*/
class Loader{
protected static $interfacePath = '';
protected static $pluginPath = '';
protected static $controllerPath = '';
/**
* Set paths to autoload classes
*
* @param string $application
* @param string $library
* @todo this part can be cleaner/smarter with less code.
* Replace "" for with constants as default folders to search
*/
public static function setPaths($autoload_paths= null)
{
if(is_array($autoload_paths)){
self::$interfacePath = array_key_exists("interface_path", $autload_paths) ?
$autoload_paths["interface_path"] : "";
self::$interfacePath = array_key_exists("plugin_path", $autload_paths) ?
$autoload_paths["plugin_path"] : "";
self::$interfacePath = array_key_exists("controller_path", $autload_paths) ?
$autoload_paths["controller_path"] : "";
}
}
/**
* Registers autoload functions
*
*/
public static function registerAutoloads() {
spl_autoload_register('Loader::loadInterface');
spl_autoload_register('Loader::loadPlugin');
spl_autoload_register('Loader::loadController');
if ( function_exists('__autoload') ) {
spl_autoload_register('__autoload');
}
}
/**
* Checks if a given file exists and load it
*
* @param string $filename
* @return bool
*/
protected static function check($filename)
{
if(file_exists($filename)){
include_once $filename;
return true;
}
return false;
}
/**
* Interface Loader
*
* @param string $className
* @return bool
*/
static function loadInterface($className)
{
return self::check(
sprintf('%s/%s_interface.php',self::$interfacePath, low($className))
);
}
/**
* Plugin Loader
*
* @param string $className
* @return bool
*/
static function loadPlugin($className)
{
return self::check(
sprintf('%s/%s_plugin.php',self::$pluginPath,low($className))
);
}
/**
* Controller Loader.
*
* @param string $className
* @return bool
*/
static function loadController($className){
$fileName = camelCaseToUnderscore($className);
return self::check(
sprintf('%s/%s_controller.php',self::$controllerPath,$fileName)
);
}
}
?>
它使用PHP的自动加载函数,所以请确保您拥有它们。
为了解决冲突,我添加了一个小的注册表类(用于唯一变量和函数的键/值存储)来修复冲突。
它还提高了性能。
对你的工作来说可能有点过分了,但这对我有帮助,因为我的项目很大。