Php 库作为Codeigniter中的单例?
我已经使用单例模式创建了一个自定义库。为什么要这样?例如,因为我需要能够在没有$this->引用的情况下调用函数,所以我可以执行以下代码:Php 库作为Codeigniter中的单例?,php,codeigniter,singleton,codeigniter-2,Php,Codeigniter,Singleton,Codeigniter 2,我已经使用单例模式创建了一个自定义库。为什么要这样?例如,因为我需要能够在没有$this->引用的情况下调用函数,所以我可以执行以下代码: function foo() { MyLibrary::instance()->foo(); } 然后我可以在控制器中调用我的函数,如下所示: function foo(); add_action('right_here', 'show_message', 11); function show_message() {
function foo() {
MyLibrary::instance()->foo();
}
然后我可以在控制器中调用我的函数,如下所示:
function foo();
add_action('right_here', 'show_message', 11);
function show_message()
{
echo "hello world!";
}
do_action('right_here');
而不是
$this->mylibrary->foo();
我遇到了麻烦,因为CodeIgniter试图实例化我的库,而最好的方法是“读取”静态实例
为什么我要这么做
我的自定义库必须从位于应用程序文件夹外的/plugins目录中的外部php文件中注册“hook”。看:
- /应用
- /插件
- /plugins/helloworld.php
class Loader{
public static $instance;
protected $hooks;
private function __construct($params = array()){
$this->hooks= array();
$this->includePlugins();
}
public static function instance()
{
if (!self::$instance)
{
self::$instance = new Loader();
}
return self::$instance;
}
public function includePlugins()
{
include_once "/plugins/helloworld.php";
}
public function do_action($hook= "after")
{
foreach ($this->actions[$hook] as $function)
{
call_user_func_array($function, array());
}
}
public function add_action($hook, $function, $priority)
{
if ($hooks !== false)
{
$this->actions[$hook][] = $function;
}
else
{
echo "hook name is unavalaible";
}
}
}
/**
* Functions using the Singleton instance !!!
*/
function do_action($hook)
{
Loader::instance()->do_action($hook);
}
function add_action($hook, $function, $priority)
{
Loader::instance()->add_action($hook, $function, $priority);
}
不,我的helloworld.php(插件)如下所示:
function foo();
add_action('right_here', 'show_message', 11);
function show_message()
{
echo "hello world!";
}
do_action('right_here');
最后,我可以在控制器/视图中调用函数do_action来打印消息,如下所示:
function foo();
add_action('right_here', 'show_message', 11);
function show_message()
{
echo "hello world!";
}
do_action('right_here');
请注意,我的所有重要函数都由一个全局函数调用,该函数允许我使用singleton实例。但我遇到两个问题:
- 在system/core/Codeigniter.php中包含您的库,如下所示: 需要_一次(“/path/to/library.php”)
- 使用&符号返回实例,如下所示:
function foo();
add_action('right_here', 'show_message', 11);
function show_message()
{
echo "hello world!";
}
do_action('right_here');
单身人士:
public static function &instance()
{
if (!self::$instance)
{
self::$instance = new Loader();
}
return self::$instance;
}
- 也可以使用您的函数了。此外,还可以包括th CI 对象在您的库中