我在我的Laravel项目中使用了repository pattern。
从其他服务调用服务的好模式是什么?
例如,服务将如下所示:
class GetAllUsersService
{
private $userRepository;
public function __construct(UserRepository $repository)
{
$this->userRepository = $repository;
}
public function execute()
{
return $this->userRepository->getAll();
}
}现在,如果我想从应用程序的其他部分执行此服务,我将执行以下操作:
class AnyClass
{
public function executeUserService()
{
$repository = new UserEloquentRepository();
$service = new GetAllUsersService($repository);
return $service->execute();
}
}这是正确的做法吗?还有别的办法吗?也许一些UI层应该在这两者之间?
发布于 2019-12-10 14:41:28
我认为你有三种方法可以做到:
1)使用__construct()方法;
class AnyClass
{
private $get_all_users_service;
public function __construct(GetAllUsersService $get_all_users_service)
{
$this->get_all_users_service = $get_all_users_service;
}
public function index()
{
$fetchAllUsers = $this->get_all_users_service->fetchAll();
}
}2)使用指定的服务,就像每个函数的一个参数需要使用它们:
class AnyClass
{
public function index(GetAllUsersService $get_all_users_service)
{
$fetchAllUsers = $get_all_users_service->fetchAll();
}
}3)像这样使用Laravel helper的方法app():
class AnyClass
{
public function index()
{
$get_all_users_service = app(GetAllUsersService::class);
$fetchAllUsers = $get_all_users_service->fetchAll();
}
}https://stackoverflow.com/questions/59260574
复制相似问题