We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Once again: Dependency Injector in static method [SOLVED]

I know this question has been answered already, but none of the answers I found are actually helping me. I would like to get access to DI from a static method. I tried using the solution mentioned in https://docs.phalcon.io/en/latest/reference/di.html#accessing-the-di-in-a-static-way

$session = Phalcon\DI::getDefault()->getSession();

but php returned a warning that "A session had already been started". Normally I wouldn't worry, but it's kind of hard to develop with this message in the way all the time. I was able to get around this problem, but I was thinking that there must be a way to solve it. Some time passed, and I was in a need of accessing dispatcher from a static function. I wanted to get the current controller and the current action inside the static function, so I used

$di = Phalcono\DI:getDefault();
$dispatcher = $di->getDispatcher();
$controllerName = $dispatcher->getControllerName();

but this is returning <uninitialized>. When I analyzed the $dispatcher it looks like it had been just instantiated, with almost all members <uninitialized>.

So my question is - how can I get the currently running DI? Am I missing something?



98.9k
Accepted
answer

Try setting the session service shared:

    $di->setShared('session', function(){
        $session = new Phalcon\Session\Adapter\Files();
        $session->start();
        return $session;
    });


9.8k

Thanks a lot! That worked. I have a question though - what is the trade-off here? Why not to set all services as shared?



98.9k

Phalcon sets services as non-shared by default, however, classes like Phalcon\DI\FactoryDefault sets most services up as shared.