我在Codeigniter中使用hook
机制。钩子的种类是post_controller_constructor
。
类钩子里面有一个私有对象:
private $settings = array();
执行hook后填充此对象。
如何从库CI和控制器访问$settings
?
类别:
<? class LCode_module
{
private $CI;
private $_default_lang = "en";
private $_sufixLangDefault = "_EN";
private $allowedLanguages = array();
private $_countryCurrent;
private $countries = array();
private $languages = array();
private $settings = array();
public function __construct()
{
$this->CI =& get_instance();
/* Load lists */
$this->CI->load->library('listdata');
$this->countries['country'] = $this->CI->listdata->country;
$this->countries['country_code'] = $this->CI->listdata->country_code;
$this->countries['country_lang'] = $this->CI->listdata->country_lang;
$this->languages = $this->CI->listdata->languages_sys;
}
public function route()
{
//Here I put data to $settings
}
}
方法route
是hook
在构造函数结束时:
/* Add object of class to GI instance */
$this->CI->LCode_module = new stdClass;
$this->CI->LCode_module->settings = &$this->settings;
我尝试在控制器中获取数据后
$CI =& get_instance();
$c = $CI->LCode_module;
var_dump($c); // NULL
答案 0 :(得分:1)
使用它作为您的类,我创建了一个静态选项,您可以随时使用它:
<?php
class LCode_module
{
private $CI;
private $_default_lang = "en";
private $_sufixLangDefault = "_EN";
private $allowedLanguages = array();
private $_countryCurrent;
private $countries = array();
private $languages = array();
private $settings = array();
private static $instance;
private static $static_settings;
public function __construct()
{
$this->CI =& get_instance();
/* Load lists */
$this->CI->load->library('listdata');
$this->countries['country'] = $this->CI->listdata->country;
$this->countries['country_code'] = $this->CI->listdata->country_code;
$this->countries['country_lang'] = $this->CI->listdata->country_lang;
$this->languages = $this->CI->listdata->languages_sys;
self::$instance = &$this;
self::$static_settings = &$this->settings;
}
public function route()
{
//Here I put data to $settings
}
public static function getInstance(){
if (is_null(self::$instance)) { self::$instance = new self(); }
return self::$instance;
}
public static function settings($key = NULL){
$instance = self::getInstance();
if(is_null($key)) return $instance::$static_settings;
return (array_key_exists($key, $instance::$static_settings) ? $instance::$static_settings[$key] : null);
}
}
然后你打电话
LCode_module::settings()
当您需要检索设置时
这确实意味着并行单独使用,这不是最佳实践,但它现在应该可以做到这一点,因为钩子只加载一次。我确信CI有办法执行此操作,但我现在正在填写空白。