查看codeigniter的源代码,
在其辅助函数中,我不断看到代码
$CI =& get_instance();
,任何人都可以向我解释该代码的工作原理吗?
我知道它正在返回对$ CI超级对象的引用,但是它get_instance()
来自哪里呢?
Answers:
它基本上是一个Singleton设计模式,它使用函数而不是静态方法。
要深入了解,请查看源代码
因此,基本上,它不强制执行单例,但这是公共函数的捷径...
编辑:其实,现在我明白了。为了与PHP4兼容,他们必须执行double-global-variable-hack使其正确返回引用。否则,引用将被搞砸。而且由于PHP4不支持静态方法(反正还是正确的),所以使用函数是更好的方法。因此由于遗留原因它仍然存在...
因此,如果您的应用程序仅是PHP5,则应该没有错CI_Base::get_instance();
,这是相同的...
$CI =& get_instance();
我在寻找该文档的文档上打了我的脸……
仅扩展CI_Controller,Model,View的类可以使用
$this->load->library('something');
$this->load->helper('something');//..etc
您的自定义类不能使用上面的代码。要在自定义类中使用上述功能,必须使用
$CI=&get instance();
$CI->load->library('something');
$CI->load->helper('something');
例如,在您的自定义课程中
// this following code will not work
Class Car
{
$this->load->library('something');
$this->load->helper('something');
}
//this will work
Class Car
{
$CI=&get_instance();
$CI->load->library('something');
$CI->load->helper('something');
}
// Here $CI is a variable.
这是一个单例结构,用于了解codeigniter如何加载库和类
<?php
/*
====================================
start of the loader class
====================================
*/
class Loader {
protected function _init_class($class){
$C = Controller::get_instance();
$name = strtolower($class);
$C->$name = new $class();
}
public function _class($library){
if(is_array($library)){
foreach($library as $class){
$this->library($class);
}
return;
}
if($library == ''){
return false;
}
$this->_init_class($library);
}
public function view ($param) {
echo $param;
}
}
/*
===============================
End of the loader class
==============================
*/
/*
===============================
start of core controller class
==============================
*/
class Controller {
private static $instance;
function __construct () {
self::$instance = $this;
$this->load = new Loader();
}
public static function get_instance(){
return self::$instance;
}
}
/*
===============================
end of the core controller class
===================================
*/
/*
====================================================
start of library sections (put all your library classes in this section)
=====================================================
*/
class MyLibrary {
private $c;
function __construct() {
$this->c = Controller::get_instance();
}
function say($sentence) {
$this->c->load->view($sentence);
}
}
/*
====================================================
End of the library sections
====================================================
*/
/*
============================================
start of controller section (put all your controller classes in this section)
===========================================
*/
class Foo extends Controller {
function __construct () {
parent::__construct();
$this->load->_class('MyLibrary');
}
function bar() {
$this->mylibrary->say('Hello World');
}
}
/*
==========================================
End of the controller sections
==========================================
*/
$foo = new Foo();
$foo->bar();
=&
在项目中的任何地方编写代码。