Php 如何将参数传递给CodeIgniter中的钩子?
在CodeIgniter中,如何从调用钩子的上下文传递参数 例如: 文件_,其中_Hook _被称为_.php:Php 如何将参数传递给CodeIgniter中的钩子?,php,codeigniter,hook,codeigniter-3,Php,Codeigniter,Hook,Codeigniter 3,在CodeIgniter中,如何从调用钩子的上下文传递参数 例如: 文件_,其中_Hook _被称为_.php: $this->hooks = load_class('Hooks', 'core'); $filename = 'example.zip'; $this->hooks->call_hook('site_export_before_delete'); # A variable with global scope should have an unique nam
$this->hooks = load_class('Hooks', 'core');
$filename = 'example.zip';
$this->hooks->call_hook('site_export_before_delete');
# A variable with global scope should have an unique name,
# to avoid conflict with any other one in your entire application.
# Choose it carefully.
global $foo_hook_file_name;
$foo_hook_file_name = $file_name;
config/hooks.php:
$hook['site_export_before_delete'][] = array(
'class' => 'Foo',
'function' => 'export_site',
'filename' => 'Foo.php',
'filepath' => 'modules/foo/controllers',
'params' => [''] # Should be $filename from File_Where_Hook_is_Called.php
);
应用程序/modules/foo/controllers/foo.php:
public function export_site($filename) {
echo $filename); # Should print $filename from File_Where_Hook_is_Called.php
}
public function export_site() {
global $foo_hook_file_name;
echo $foo_hook_file_name;
}
它很糟糕,但是使用了global
scoped变量。
由于CI_hook类下的函数call_hook
,因此不接受其他参数:
public function call_hook($which = '') {
#...
}
由于我不想直接修改CodeIgniter中的核心文件,我最终使用了一个全局变量范围:
文件_,其中_Hook _被称为_.php:
$this->hooks = load_class('Hooks', 'core');
$filename = 'example.zip';
$this->hooks->call_hook('site_export_before_delete');
# A variable with global scope should have an unique name,
# to avoid conflict with any other one in your entire application.
# Choose it carefully.
global $foo_hook_file_name;
$foo_hook_file_name = $file_name;
应用程序/modules/foo/controllers/foo.php:
public function export_site($filename) {
echo $filename); # Should print $filename from File_Where_Hook_is_Called.php
}
public function export_site() {
global $foo_hook_file_name;
echo $foo_hook_file_name;
}
只需确保在全局变量前面加上一个唯一的名称,例如钩子的名称,以避免与其他变量发生冲突。我知道可能有点晚了,但我偶然发现了你的问题,因为我有同样的需要,并以正确的方式解决了它 根据,您可以通过实现自己的MY_Hooks类来覆盖默认的CI_Hooks类行为,通常位于
application/core/MY_Hooks.php
可以使用Codeigniters“配置类”。。。。我检查了codeigniters在调用钩子后面的源代码,它的定义类似于公共函数调用钩子($which='')
,所以它没有可以传递的参数。是的,我也这么做了。有点奇怪,对吧?还是一种建筑选择?@RaymondNijland,我最终使用了global。