我有以下钩子配置(在hooks.php中)
$hook['post_controller_constructor'][] = array(
'class' => 'MY_DataCollection',
'function' => 'init',
'filename' => 'MY_DataCollection.php',
'filepath' => 'hooks'
);
$hook['post_controller'][] = array(
'class' => 'MY_DataCollection',
'function' => 'post_controller',
'filename' => 'MY_DataCollection.php',
'filepath' => 'hooks'
);
我想要做的是在post_controller_constructor
中实例化类,然后运行init
方法。然后,post_controller
运行post_controller
,但使用相同的实例。 CodeIgniter然后再次实例化该类。
接下来我尝试了一些我认为有点聪明的东西:
require_once APPPATH . 'hooks/MY_DataCollection.php';
$collection = new MY_DataCollection;
$hook['post_controller_constructor'][] = array(
'function' => array($collection, 'init'),
'filename' => 'MY_DataCollection.php',
'filepath' => 'hooks'
);
$hook['post_controller'][] = array(
'function' => array($collection, 'post_controller'),
'filename' => 'MY_DataCollection.php',
'filepath' => 'hooks'
);
这不起作用,因为CI中的钩子类确实需要我得到:
Fatal error: Cannot redeclare class MY_DataCollection in /var/www/application/hooks/MY_DataCollection.php on line 7
所以我摆脱了文件路径信息:
require_once APPPATH . 'hooks/MY_DataCollection.php';
$collection = new MY_DataCollection;
$hook['post_controller_constructor'][] = array(
'function' => array($collection, 'init')
);
$hook['post_controller'][] = array(
'function' => array($collection, 'post_controller')
);
甚至没有尝试投放,就像在CI_Hooks
课程中有_run_hook
进行此检查一样:
if ( ! isset($data['filepath']) OR ! isset($data['filename']))
{
return FALSE;
}
我想我必须通过扩展这个课程来覆盖这个功能,但是我不能相信之前没有其他人遇到这种情况而且那里有#39 ;不是更容易解决它的方法。
由于
答案 0 :(得分:4)
嗯,似乎你需要在某处存储所需类的实例。 也许你可以这样做:
class MyHooks
{
public static $object_you_need;
public function init()
{
$object = new MyObject();
$object->init();
self::$object_you_need = $object;
}
public function post_controller()
{
$object = self::$object_you_need;
// do stuff with that object
}
}
感觉不好,但我觉得它很有效。
答案 1 :(得分:3)
此问题已在 CI3上解决以下是如何解决 CI2
MY_Hooks.php
app/core directory
即可
Hooks.php
类并将其放入您的
MY_Hooks.php
,但班级名称MY_Hooks Extends
CI_Hooks
位于system/core/hooks.php
call_hook
功能更改为_call_hook
(只需添加下划线'_')private _run_hook
更改为public
这是测试它是否正常工作
class Hook_hook{
private $init = 'function inits not called';
public function inits(){
$this->init = 'function inits called';
}
public function load(){
echo '<script>alert("'.$this->init.'")</script>';
}
}
config / hooks.php
上的示例配置$hook['post_controller_constructor'][] = array(
'class' => 'Hook_hook',
'function' => 'inits',
'filename' => 'Hook_hook.php',
'filepath' => 'hooks'
);
$hook['post_controller'][] = array(
'class' => 'Hook_hook',
'function' => 'load',
'filename' => 'Hook_hook.php',
'filepath' => 'hooks'
);