[英]Codeigniter/PHP include re-useable functions in controller
我拥有不断在我的控制器中重复使用的此功能。 我决定将其移动到可以一直引用的文件中。 这是我的文件结构
controllers
|Generic
|Users
|get_all_languages.php
|Users
|Lang
|Lang.php
我想引用其中包含的get_all_languages
<?php
function get_all_languages(){
$this->curl->create(GetAllLanguages);
$this->curl->http_login(REST_KEY_ID,REST_KEY_PASSWORD);
return json_decode($this->curl->execute(),true);
}
到目前为止,我已经尝试将其包含在文件的顶部,例如:
<?php
include __DIR__.'/../../Generic/Users/get_all_languages.php';
class Lang extends CI_Controller{
但是,当我尝试使用$ this-> get_all_languages();之类的函数时,发生错误,提示调用未定义的方法Lang :: get_all_languages()
我也尝试在__contruct之后包含它,但不允许我编译。
我希望有人能让我知道如何引用该功能。
谢谢。
您可以使用library
或codeigniter的helper
。
您可以在application/config/autoload.php
自动加载它们。(请参考 )
如果需要特定的控制器,则可以使用$this->load->library()
或$this->load->helper()
在控制器的构造中使用它。
例如:
class A extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('libraryname');
$this->load->helper('helpername');
}
public function index() {...}
...
}
...
更新
application/helpers/global_lang_helper.php
<?php
function get_all_languages(){
$CI = &get_instance();
$CI->load->library('curl');
$CI->curl->create(GetAllLanguages);
$CI->curl->http_login(REST_KEY_ID,REST_KEY_PASSWORD);
return json_decode($CI->curl->execute(),true);
}
在您的控制器...
public function __construct()
{
parent::__construct();
$this->load->helper('global_lang');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.