欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

003 - CI在你的类库中使用 CodeIgniter 资源

程序员文章站 2022-05-10 12:58:18
...

在你的类库中使用 get_instance() 函数来访问 CodeIgniter 的原生资源,这个函数返回 CodeIgniter 超级对象。

通常情况下,在你的控制器方法中你会使用 $this 来调用所有可用的 CodeIgniter 方法:


$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
// etc.

但是 $this 只能在你的控制器、模型或视图中直接使用,如果你想在你自己的类中使用 CodeIgniter 类,你可以像下面这样做:

首先,将 CodeIgniter 对象赋值给一个变量:

$CI =& get_instance();

一旦你把 CodeIgniter 对象赋值给一个变量之后,你就可以使用这个变量来 代替 $this

$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.


注解:

你会看到上面的 get_instance() 函数通过引用来传递:


$CI =& get_instance();

这是非常重要的,引用赋值允许你使用原始的 CodeIgniter 对象,而不是创建一个副本。


然类库是一个类,那么我们最好充分的使用 OOP 原则,所以,为了让类中的所有方法都能使用 CodeIgniter 超级对象,建议将其赋值给一个属性:

class Example_library {

    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()
    {
        echo $this->CI->config->item('base_url');
    }

}

相关推荐:

002 - PDO和MySQLi区别与选择

001 - PDO 用法详细解析

以上就是003 - CI在你的类库中使用 CodeIgniter 资源 的详细内容,更多请关注其它相关文章!