CodeIgniter Load File with data parameter

2019-08-02 12:47发布

问题:

Is there any option in CodeIgniter to load files with parameters like in views?

In my Controller I load this File:

$path_to_logic = "extended_core/plugins/saphir_e-cms/be_extensions/$this->modul_id/package/logic.php";     
$logic = $this->CI->load->file($path_to_logic, true);

I have an array() in the controller that I would pass to the loaded file, like the $data var in the views.

回答1:

You need to add this functionality into the Loader class.

In order to do that, create a new file named MY_Loader.php inside the application/core/ folder, as follows:

/**
* My Custom Loader
*/
class MY_Loader extends CI_Loader
{   
    function __construct()
    {
        parent::__construct();
    }

    /**
     * Custom File loader method
     *
     * @param  string  $path
     * @param  array   $vars
     * @param  bool    $return
     * @return void
     */
    public function file($path, $vars = array(), $return = FALSE)
    {
        return $this->_ci_load(array(
            '_ci_path' => $path,
            '_ci_vars' => $this->_ci_object_to_array($vars),
            '_ci_return' => $return
        ));
    }
}

Then load the file with values as follows:

$logic = $this->CI->load->file($path_to_logic, array('foo' => 'bar'), true);

Inside the file you'll have $foo.



回答2:

Why not assign it something like this..

$this->CI->custom_array = array();
$this->CI->custom_array = // Load in array data via function etc..

And then use that within the view etc.