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.

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.



85.4k
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?