benedmunds / CodeIgniter-Ion-Auth

Simple and Lightweight Auth System for CodeIgniter
http://benedmunds.com/ion_auth/
MIT License
2.35k stars 1.14k forks source link

ionAuth as CI4 service? (question) #1567

Open dgvirtual opened 2 years ago

dgvirtual commented 2 years ago

Hi, I am using ionAuth in codeigniter filters and am wondering if calling in each filter (and then in the baseController)

$ionAuth = new \IonAuth\Libraries\IonAuth();

is perhaps not optimal in terms of performance... Does it hit the database each time I do it? How do I get the shared instance of the class in the filters?

I see calling CI libraries as services returns a shared class, so is there any value in defining IonAuth also as a service? If so, maybe someone has it done already and could share?

Sorry if these questions sound silly, I am not very good at OOP...

benedmunds commented 2 years ago

Yes that's definitely inefficient.

I would define an auth class property in your base controller and then use that in the filters. Here's an example of doing that in CI4: https://stackoverflow.com/questions/58900176/codeigniter-4-autoload-library

dgvirtual commented 1 year ago

Unless I messed something up in my tests, the filters' method before() seems to run before the BaseController method initController, so I cannot define auth class property in the BaseController.

But I have implemented ionAuth as a service this way:

added a service method in the app/Config/Services.php class:

    public static function ionAuth($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('ionAuth');
        }
        return new \IonAuth\Libraries\IonAuth();
    }

And then in both BaseController's initController method and the filters I can run

$this->ionAuth = \Config\Services::ionAuth();

without worrying which of them runs first...