'Apply injection to call in methods yii2

I have several services which calls in Controllers. How I can replace next rows:

$service = new UserService() $service->login();

to:

$userService->login();

I'm using it in few Controllers, maybe need to make changes in config or something.. I didn't found such cases in yii2 docs.



Solution 1:[1]

Make parent controller with this code in it:

private $userService;

public function __construct($id, $module, UserService $userService, $config = [])
{
    $this->userService= $userService;
    parent::__construct($id, $module, $config);
}

Extends all controllers with your new controller (BaseController for example).

Then in your action you can use it like:

$this->userService->login();

If it is not what do you seraching for... please give more information

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vvpanchev