O. *_*dze 6 php model-view-controller traits laravel eloquent
我有一个简单的问题,我正在努力回答,我希望你们能帮助我。所以我正在 Laravel 上开发应用程序。我想让控制器清晰,所以我在模型类本身中有复杂的查询(我不想使用存储库)。如果我想要一些将用于许多模型的功能,我会将这个功能放在特征中并在需要时使用它。所以这是我的问题.. 我需要服务类吗?特征还不够吗?
假设您有一个需要Cat
模型和Dog
模型的特征中的方法。每次使用该特性时,您都需要传入一个实例Cat
和一个实例Dog
以使其工作。
最终会变得很累。如果你最终添加了一个特性,而这个特性现在需要一个Bird
模型,会发生什么?现在你有很多代码需要修改,只是为了Bird
在每次你想使用它时开始将 传递给 trait 中的方法。
这是服务类变得非常方便的地方。在服务类的构造函数,你可以注入User
,Permission
以及Role
模型是这样的...
public function __construct(Cat $cat, Dog $dog, Bird $bird)
{
$this->cat = $cat;
$this->dog = $dog;
$this->bird = $bird;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以向你的应用程序添加一个服务提供者,它通过传入适当的模型来指示 Laravel 如何创建这个服务类。从那里,您可以将此服务自动注入到您的控制器中,因为您认为适合当前您只是为此使用 trait 的地方。
这意味着如果您需要添加依赖项,您只需要更新一个,可能是两个文件。服务类本身向构造函数和可能的服务提供者添加附加项。所有使用它的控制器都不需要更新以将这些额外的项目传递给构造函数,因为它是由 Laravel 处理的(更合适的是 IoC 容器)。
这对于测试也是非常有益的。将依赖项注入到类中时,设置测试环境来模拟这些依赖项比尝试动态构建模拟以传递到 trait 方法更容易。测试特征也更加困难,因为use
为了测试特征的方法,需要对该特征进行某些操作。
// we can use a service provider to tell laravel how to create this service (https://laravel.com/docs/5.7/providers)
class PetService
{
protected $cat;
protected $dog;
protected $bird;
public function __construct(Cat $cat, Dog $dog, Bird $bird)
{
$this->cat = $cat;
$this->dog = $dog;
$this->bird = $bird;
}
public function doStuff()
{
// does things with $this->cat, $this->dog, $this->bird
}
}
class PetController
{
// use PetTrait;
protected $petService;
// laravel will automatically create the PetService for us and pass it into the constructor when building this controller (https://laravel.com/docs/5.7/container)
public function __construct(PetService $petService)
{
$this->petService = $petService;
}
public function someControllerMethod()
{
// $this->doStuff(new Cat, new Dog, new Bird); // In order to modify this method, we need to update each time it's used.
$this->petService->doStuff(); // We don't need to worry about passing in arguments since it's handled by the service container when constructing the pet service and can make changes without updating each controller that uses it.
}
}
Run Code Online (Sandbox Code Playgroud)
并进一步细谈,如果你决定会发生什么Bird
现在需要的一个实例Chicken
,Turkey
,Dodo
为了让它正常工作。现在,您需要再次检查使用Bird
和更新每个特征的任何特征,以传入其每个依赖项的实例。
这就是为什么使用服务容器和提供者来规划和构建服务类的依赖项是有利的。它极大地提高了应用程序的可维护性。到目前为止,它在非常大且复杂的应用程序中最为有益。
但是,如果您的应用程序相当简单,它可能没有那么有用,甚至可能会增加不必要的复杂性,并且如果特征对您更有意义,那么实际上在那时使用它们可能会更好。让您的应用程序在不需要时灵活地使用服务是不好的。
归档时间: |
|
查看次数: |
2527 次 |
最近记录: |