passing data from hook to view in codeigniter

两盒软妹~` 提交于 2019-12-03 15:23:25
splash58

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

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.

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));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!