在代码点火器中调用helper和library的方法有什么区别吗?

时间:2014-02-10 08:59:22

标签: php codeigniter codeigniter-2 codeigniter-helpers

我有点困惑,在代码点火器中使用库和帮助器的方法。我还在学习代码点火器。

CONTROLLER

function index(){
    $this->load->helper('text');
    $this->load->library('auth'); //custom library

    $data['string'] = 'this is sample ..... this is sample';
    $this->load->view('article', $data);
}

查看

<?php 
if(is_logged_in()){    //is_logged_in() is the method from the library, 'auth'
    echo 'You are logged in';
}
<p><?php echo word_limiter($string, 10); ?></p> <!--word_limiter() is the method from the helper, 'text' -->

在上面的视图文件中,辅助方法word_limiter()正常工作。但方法is_logged_in()不起作用。但如果我这样做($this->auth->is_logged_in()),它就会奏效。

但是为什么来自助手的方法,即word_limiter()不必像这样($this->text->word_limiter())。

调用helper和library的方法有什么区别吗?

2 个答案:

答案 0 :(得分:26)

CodeIgniter帮助程序是一组相关的函数(公共函数),您可以在模型视图控制器中使用它们。无处不在。

加载(包含)该文件后,您可以访问这些功能。

但是库是一个类,你需要创建一个类的实例($this->load->library())。您需要使用对象$this->...来调用方法。

作为一个拇指规则:一个库用于面向对象的上下文(Controller,...),而一个帮助器更适合在 Views 中使用(非面向对象)。

答案 1 :(得分:3)

CI助手可能有也可能没有上课

但是图书馆必须有班级代表。

参考这个答案

CodeIgniter: Decision making for creating of library & helper in CodeIgniter