CodeIgniter Forums
Possible issue with router->controllerName() - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Possible issue with router->controllerName() (/showthread.php?tid=92145)



Possible issue with router->controllerName() - Fido L Dido - 12-11-2024

Hi there,
In a filter I'm doing the following:
Code:
  public function before(RequestInterface $request, $arguments = null)
    {
        $router = \Config\Services::router();
        $method = $router->methodName();
        $controllerNameArray = explode("\\", $router->controllerName()); # breaks CI hot reload

This works fine until I turn on "hot reload" whereby I get the following error in the log file:

Code:
CRITICAL - 2024-12-11 12:54:32 --> TypeError: explode(): Argument #2 ($string) must be of type string, Closure given
[Method: GET, Route: __hot-reload]
in APPPATH/Filters/Auth.php on line 35.
1 APPPATH/Filters/Auth.php(35): explode()

It's not critical as I rarely use hot reload, however it could also be me doing something wrong.


RE: Possible issue with router->controllerName() - Fido L Dido - 01-09-2025

Nobody has picked up on this so I have investigated further.

I have noticed that my "before" filter is called twice on an initial page load when hot load is enabled. I don't know why this is. On the one call the controllerName() function returns the correct string, but on the other call it returns a Closure object which is what is breaking my code.

I've modified my code so that my "before" filter simply returns if this condition is false:

PHP Code:
$controllerName $router->controllerName();
if (!
is_string($controllerName)) {
    log_message('debug''skipping before filter');
    return;            


This seems to have fixed the problem without compromising what the filter is doing.