Search code examples
phpcodeignitercodeigniter-2

CodeIgniter Load File with data parameter


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.


Solution

  • 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.