Search code examples
codeignitercodeigniter-3codeigniter-4

How to autoload codeigniter4 library once and access it every where in Controller, Model, View like in CI3


In CI3 we make custom library and auto-load it in config/autoload.php then we able to use it everywhere in controller,model,view by simple $this->rules->status() where Rules is library in application/library folder

But unable to do the same thing in CI 4, is there any alternate available for this


Solution

  • If you want to load your own library you have to rely on namespaces and create a new object whenever you want to use this lib. Also be sure to check app/Config/Autoload.php file so your custom lib is known by the autoloader.
    Since codeigniter 3 superobject has been removed you can't access it everywhere whenever you want. However you can load it into a view, a controller and a model and make your views, controllers and models extending it.

    For example a lib named FooLib which is in app/Librairies will be :

    namespace App\Libraries;  
    
      class FooLib {
    
        public function __construct() {
          // your constructor
        }
    
        // ...
        
       }
    

    And if you want to call it in a Controller :

    namespace App\Controllers;
    
    use App\Libraries\FooLib;
    use CodeIgniter\Controller;
    
    class FooController extends Controller {
    
        protected $lib;
    
        public function __construct() {
            $this->lib = new FooLib();
        }
    }
    

    And make sure to add it to the autoloader in app/Config/Autoload.php by modifing$psr4 variable if your lib folder is outside of the app folder.

    $psr4 = [
                'App'         => APPPATH,                // To ensure filters, etc still found,
                APP_NAMESPACE => APPPATH,                // For custom namespace
                'Config'      => APPPATH . 'Config',
                'Libraries'   => APPPATH . 'Libraries'   // Your custom librairies
            ];