Search code examples
codeignitercodeigniter-4

How can I make a library globally accessible in codeiginter4


I have a library with lot of functions which I need all around the controllers, helper, models etc.

Also I want to reduce the code inside each part of them.

So I try to init the library once and have it available globally.

To include it into the basecontroller/basemodel failed, I only find the normal way about namespace and get the library by "$mylib=new Mylib"();", this both rows of code I don't to avoid. Also it will be nice, if its the same instance to reduce resources and not get every time a new instance for the same functions...

I look around about factories and services, but I don't understand the way like both works, also I couldn't find a simple complete example from including, define function and call them with params, so I think services or factories can be a way for it?

So is there a way to make a library globally available?


Solution

  • In the meantime i've found a way to make my library avivable in controllers, models, helpers and views without creating a new instance of them.

    the follwing way works for me

    1. base_controller on initController i create my lib-instance "$this->mylib = new mylib();"

    2. to make them aviable in other controllers i need to add take care to have "use App\Controllers\BaseController;" and add "use App\Libraries\Mylib;" now in the controller with "$this->mylib->myfunction()" the lib-instance is avivable.

    3. to make it also avivable in views etc. inspired by this post: Codeigniter 4 - get instance in helper function so a) $CI_INSTANCE = []; # It keeps a ref to global CI instance function register_ci_instance(\App\Controllers\BaseController &$_ci) { global $CI_INSTANCE; $CI_INSTANCE[0] = &$_ci; } function get_instance(): \App\Controllers\BaseController { global $CI_INSTANCE; return $CI_INSTANCE[0]; }

    b) go back to basecontroller and add in the initcontroller part

    register_ci_instance($this);
    

    c) Now with

    $ci = &get_instance();      
    $ci->mylib->myfunction();
    

    is avivable.

    For me it works, hope it helps.