passing data from hook to view in codeigniter

2019-03-29 23:20发布

can i passing data from hook to view, If is it possible please explain.

for example

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

i want send some array data varify_project.php(hook file) to view.

3条回答
贪生不怕死
2楼-- · 2019-03-29 23:56

I do so

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";
} ;
查看更多
小情绪 Triste *
3楼-- · 2019-03-29 23:56

If you are wanting to add additional data at the time of loading the view, you could extend the core loader class like this:

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));
    }
}

the $vars['hello'] would then create a variable that you can use in any view called $hello and could be repeated to create any number of variables providing that you wanted them to be used on every page in your application.

查看更多
一夜七次
4楼-- · 2019-03-30 00:08

I don't have enough rep to comment splash58's answer so I'm adding this here in case it is useful to someone.

Due to _ci_object_to_array() not being available anymore and sending an error the custom loader code should be (as it is in core since 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));
    }
}
查看更多
登录 后发表回答