Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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

$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?


Try setting the session service shared:

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


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


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