What are the different ways of dependency injection in Laravel?
In Laravel, dependency injection can be achieved using the following methods:
- Constructor injection involves declaring dependencies in a class’s constructor and passing those dependencies as parameters to the constructor.
Sample code:
class UserController
{
protected $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function index()
{
// 使用 $this->userService 调用相关方法
}
}
- Method injection: declaring dependencies within a method and passing them as parameters to the method.
Example code:
class UserController
{
protected $userService;
public function index(UserService $userService)
{
$this->userService = $userService;
// 使用 $this->userService 调用相关方法
}
}
- Service container: Resolve dependencies using Laravel’s service container.
Example code:
class UserController
{
protected $userService;
public function index()
{
$this->userService = app(UserService::class);
// 使用 $this->userService 调用相关方法
}
}
These are several common ways of dependency injection, you can choose the suitable method according to the specific situation.