在某些情況下,你可能需要開(kāi)發(fā)一個(gè)類(lèi),這個(gè)類(lèi)能使用控制器一部分功能。
在你的控制器方法中初始化的任何類(lèi),都可以訪(fǎng)問(wèn) CodeIgniter 原生資源,簡(jiǎn)單通過(guò)使用 get_instance()
函數(shù)。這個(gè)函數(shù)回傳 CodeIgniter 對(duì)象。
通常來(lái)說(shuō),調(diào)用任何 CodeIgniter 方法需要你使用 $this
結(jié)構(gòu):
$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
// etc.
然而,$this
僅能再你的控制器,數(shù)據(jù)模型,視圖中使用。如果你想在你的類(lèi)中使用 CodeIgniter 類(lèi),可以參考以下做法:
首先,將 CodeIgniter 對(duì)象賦值給變量:
$CI =& get_instance();
一旦你將對(duì)象賦值給變量,你可以使用變量實(shí)例取代 $this
:
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.
如果在其他類(lèi)中使用 get_instance()
,可以將它賦給一個(gè)屬性。通過(guò)這個(gè)方法,你不需要在每個(gè)方法中調(diào)用 get_instance()
。例如:
class Example {
protected $CI;
// We'll use a constructor, as you can't directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function foo()
{
$this->CI->load->helper('url');
redirect();
}
public function bar()
{
$this->CI->config->item('base_url');
}
}
在上述的例子中,foo()
和 bar()
方法將會(huì)在你實(shí)例化的子類(lèi)工作,不需要每次都調(diào)用 get_instance()
。