将数据从挂钩传递到 codeigniter 中的视图

passing data from hook to view in codeigniter

我可以将数据从钩子传递到视图吗,如果可以请解释一下。

例如

 $hook['post_controller_constructor'][] = array(
    'class'    => 'Varify_user',
    'function' => 'user_project',
    'filename' => 'varify_project.php',
    'filepath' => 'hooks',
    'params'   => array('')
);

我想发送一些数组数据varify_project.php(挂钩文件)来查看。

如果您想在加载视图时添加额外的数据,您可以像这样扩展核心加载器class:

application/core/MY_Loader.php

<?php
class MY_Loader extends CI_Loader {
    public function view($view, $vars = array(), $return = FALSE)
    {
        $vars['hello'] = "Hello World";
        return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
    }
}

然后 $vars['hello'] 将创建一个变量,您可以在任何名为 $hello 的视图中使用该变量,并且可以重复创建任意数量的变量,前提是您希望它们在每个页面上使用在您的申请中。

我这样做

application/core/MY_Loader.php

class MY_Loader extends CI_Loader {
    static $add_data = array();
    public function view($view, $vars = array(), $return = FALSE)
    {
       self::$add_data = array_merge($vars, self::$add_data);
       return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array(self::$add_data), '_ci_return' => $return));
    }
}

application/config/hooks.php

$hook['post_controller_constructor'] = function() {
    MY_Loader::$add_data['hello'] = "Hello World";
} ;

我没有足够的代表发表评论 所以我在这里添加它以防它对某人有用。

由于 _ci_object_to_array() 不再可用并发送错误,自定义加载程序代码应该是(因为它自 3.1.3 以来就在核心中):

class MY_Loader extends CI_Loader {

    static $add_data = array();

    public function view($view, $vars = array(), $return = FALSE)
    {
       self::$add_data = array_merge($vars, self::$add_data);
       return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars(self::$add_data), '_ci_return' => $return));
    }
}