CodeIgniter-Ion-Auth
CodeIgniter-Ion-Auth copied to clipboard
ionAuth as CI4 service? (question)
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...
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
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...