Muhammad Raheel
Muhammad Raheel

Reputation: 19882

How to get rid of &get_instance() in Codeigniter

I have been using CI for two years now. One thing that really annoys me is the use of &get_instance(). Although it is halpful while we are inside library , helper , presenters , model etc. But everytime loading it is cumborsome. If you forget loading it somewhere and simply use $this->blah->blah() instead of $CI->blah->blah() this makes too much trouble and if you are working online you face the client who is complaining that he sees the error. I have seen in the laravel that you does not need to load the instance anywhere throughout the application. This is because laravel is autoloading all the libraries and models and both are available anywhere in the application. But this seems to me disadvantage why loading classes that are not required in some particular places. This tells me Codeigniter is flexible but still i want an alternative where i dont want to use &get_instance(). Any idea or suggestion ? Please.

Upvotes: 1

Views: 420

Answers (1)

Aurel
Aurel

Reputation: 3740

In your model or Core model or library

//class MY_Model extends CI_Model 
//class SomeLibrary

class Some_model extends CI_Model {  

        private $_CI;

        public function __construct() {
            parent::__construct(); //for model or core model

            $this->_CI =& get_instance();
        }   

        //if you called attributs who does not exist in that class or parent class
        public function __get($key)
        {
            return $this->_CI->$key;
        }

        //if you called methods who does not exist in that class or parent class
        public function __call($method, $arguments)
        {
            call_user_func_array(array($this->_CI, $method), $arguments );
        }

        public function test() {
            var_dump($this->some_controller_key);
            var_dump($this->some_lib_loaded);
        }
}

*NOT TESTED YET

Inspired by an piece of code from the awesome Flexi Auth

    //from a Model to keep access of CI_Controller attributs
    public function &__get($key)
    {
        $CI =& get_instance();
        return $CI->$key;
    }

I was shocked when I saw that ^^

To explain the &__get, i think when you will call this magic method a second time PHP will do not execute it again, but will take his result from the first call.

Upvotes: 1

Related Questions