Programming Codeigniter Ancillary Classes: Use $this in Codeigniter helper or library

Ancillary Classes: Use $this in Codeigniter helper or library

Ancillary Classes: Use $this in Codeigniter helper or library

In some cases, we need to create such types of classes and functions that are not actually the controllers but we also need CodeIgniter’s resources functionality. These classes may include any library class that we need to define, or a library function or helper or any other. CodeIgniter provides such classes the ability to utilize all of CodeIgniter’s resources by using get_instance() function. This is like using $this in Codeigniter helper or library

How to use $this in CodeIgniter helper or libraries

CodeIgniter get_instance()

get_instance() is the Reference to the main CI_Controller  controller’s instance. This function returns the main CodeIgniter object.

get_instance ()
Returns: Reference to your controller’s instance
Return type: CI_Controller

How get_instance() work in CodeIgniter

If you want to use all the resources of CI_Controller in any of your helpers or library then you have to create an instance in that particular helper or library. Assign this instance to a variable like I am assigning to $CI in the code below. Now this variable ($CI) will work exactly the same as $this in our controllers. You can easily load any model, helper, library, etc. to any of the libraries or helper function even not being as CI_Controller’s child class. Also, you can access any configurations and much more that you can experiment with the code.

Thus now you can use all the functions of CI in your helper or libraries itself.

Here $this does not work, here you have to use $ CI (by which name the object is created) because $this is always used to call a function or property inside the same class or child class. Whereas there is no such class, it is not possible to use $this here but as I explained above $CI is going to work as $this in such a case.

Similarly, you can use all the resources of all CIs by creating an object of CI in the library too. in this way, we can use a replicated $this in Codeigniter helper or library

By doing this a load of your Controller will be reduced and you can do all the work in the helper and library itself, you do not need to write all the code in the Controller itself.

Leave a Reply