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

Testing Phalcon App - phpunit

What's different code?

$this->userService->getUser();

and

$this->di->get('userService')->getUser();

I use it in controller.

When I testing controller use phpunit, works only the second variant.



98.9k
Accepted
answer

$this->userService obtains a shared service which means it always returns the same instance. $this->di->get('userService') is creating a new instance every time it is called.

Yeah, that's clear that $this->userService always returns the same instance, but this instance is a part of $this but of DI. How does get method of injectable work? Does it create an instance right when it calls property? If yes than it should be no difference with $this->di->get(...) at the first call.

What we do is:

  1. Create DI and define injections etc. $di->set('userService', array(.....)) We inject dependencies as properties.

  2. $ctrl = new MyController(); $ctrl->setDI($di) (our $di)

  3. $ctrl->someMethod();

function someMethod() // of MyConroller { $this->userService->; and $this->di->get('userService')->

}

In this case, when we write $this->userService, shouldnt it create new instance? Yes, if we will write the smae $this->userService it's the same instance. So what is the difference between $this->userService and $this->di->get('userService') in this case?