在 CodeIgniter 的控制器方法中添加 post_system 钩子
Adding a post_system hook from inside a controller method in CodeIgniter
我有一些代码我想在请求发送到客户端并关闭后工作,所以我想从控制器内部向系统添加一个 post_system
挂钩,所以 post_system
钩子仅在调用特定方法时运行。
CodeIgniter
是否允许在某些解决方法中这样做?
我的版本是3.0rc3
应该是可以的。一种方法是按照文档 - $config['enable_hooks'] = TRUE;
中的描述设置 post_system 挂钩,在 application/config/hooks.php
中定义挂钩,然后编写挂钩 class.
在将使用 post_system 挂钩的控制器中定义一个变量,该变量将用于决定挂钩函数是否应该 运行。在构造函数中将默认值设置为 FALSE,并在您想到的特定方法中将其设置为 TRUE。
检查 post_system_hook 函数中此变量的值。您可能希望首先检查控制器是否应该挂钩。假设 class 是 'Welcome';
post_system_hook_function(){
//the type of $CI will be the name of the controller
if(get_class($CI) !== 'welcome') {
return false;
}
if(! $var_that_flags_do_the_task){
return false
}
//do post system code here
}
我知道你想检查一个控制器,就像它是否允许像记录一样在里面。
您需要在 application/config/config 中启用挂钩。php
$config['enable_hooks'] = TRUE;
然后您需要在 application/config/hooks.php 中添加此行,代码为
$hook['pre_controller'] = array(
'class' => 'PreLogin',
'function' => 'auth',
'filename' => 'PreLogin.php',
'filepath' => 'hooks'
);
在你的 apllication/hooks/PreLogin.php
class PreLogin{
public function __construct(){
$CI =& get_instance();
$this->CI->load->library('session');
}
public function auth(){
if( ! isset($this->CI->session->userdata('id'))){
$this->CI->session->set_flashdata('error', 'You do not have permission to enter this url');
redirect(base_url(), 'refresh');
}
}
}
我有一些代码我想在请求发送到客户端并关闭后工作,所以我想从控制器内部向系统添加一个 post_system
挂钩,所以 post_system
钩子仅在调用特定方法时运行。
CodeIgniter
是否允许在某些解决方法中这样做?
我的版本是3.0rc3
应该是可以的。一种方法是按照文档 - $config['enable_hooks'] = TRUE;
中的描述设置 post_system 挂钩,在 application/config/hooks.php
中定义挂钩,然后编写挂钩 class.
在将使用 post_system 挂钩的控制器中定义一个变量,该变量将用于决定挂钩函数是否应该 运行。在构造函数中将默认值设置为 FALSE,并在您想到的特定方法中将其设置为 TRUE。
检查 post_system_hook 函数中此变量的值。您可能希望首先检查控制器是否应该挂钩。假设 class 是 'Welcome';
post_system_hook_function(){
//the type of $CI will be the name of the controller
if(get_class($CI) !== 'welcome') {
return false;
}
if(! $var_that_flags_do_the_task){
return false
}
//do post system code here
}
我知道你想检查一个控制器,就像它是否允许像记录一样在里面。
您需要在 application/config/config 中启用挂钩。php
$config['enable_hooks'] = TRUE;
然后您需要在 application/config/hooks.php 中添加此行,代码为
$hook['pre_controller'] = array(
'class' => 'PreLogin',
'function' => 'auth',
'filename' => 'PreLogin.php',
'filepath' => 'hooks'
);
在你的 apllication/hooks/PreLogin.php
class PreLogin{
public function __construct(){
$CI =& get_instance();
$this->CI->load->library('session');
}
public function auth(){
if( ! isset($this->CI->session->userdata('id'))){
$this->CI->session->set_flashdata('error', 'You do not have permission to enter this url');
redirect(base_url(), 'refresh');
}
}
}