php 在代码点火器中调用助手和库的方法有区别吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21672694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a difference between the method of helper and library are called upon in code igniter?
提问by Nirmalz Thapaz
I am getting little bit confused, the way the methods of library and helper are used in code igniter. I am still learning code igniter.
我有点困惑,在代码点火器中使用 library 和 helper 的方法的方式。我还在学习代码点火器。
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);
}
VIEW
看法
<?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' -->
In the above view file, the helper method word_limiter()works fine. But the method is_logged_in()does not work. But if I do ($this->auth->is_logged_in()), it will work.
在上面的视图文件中,helper 方法word_limiter()工作正常。但该方法is_logged_in()不起作用。但是如果我这样做($this->auth->is_logged_in()),它会起作用。
But why the method from helper i.e. word_limiter()does not have to be written like this ($this->text->word_limiter()).
但是为什么helper ie 的方法word_limiter()不必这样写($this->text->word_limiter())。
Is there a difference between the method of helper and library are called upon ?
调用 helper 和 library 的方法有区别吗?
回答by Hashem Qolami
A CodeIgniter helper is a set of related functions (Common functions) which you could use them within Models, Views, Controllers,.. everywhere.
CodeIgniter 助手是一组相关的函数(通用函数),您可以在模型、视图、控制器等任何地方使用它们。
Once you load (include) that file, you can get access to the functions.
加载(包含)该文件后,您就可以访问这些函数。
But a Library is a class, which you need to make an instance of the class (by $this->load->library()). And you'll need to use the object $this->...to call the methods.
但是 Library 是一个类,您需要创建该类的实例 (by $this->load->library())。并且您需要使用该对象$this->...来调用方法。
As a thumb rule:A library is used in object oriented context (Controller, ...), while a helper is more suitable to be used within the Views(non object oriented).
作为一个经验法则:库用于面向对象的上下文(控制器,...),而助手更适合在视图中使用(非面向对象)。
回答by Kumar V
CI Helper may or may not have class
CI 助手可能有也可能没有类
But Library must have class representation.
但是图书馆必须有类表示。
Refer this SO Answer
请参阅此 SO 答案
CodeIgniter: Decision making for creating of library & helper in CodeIgniter

