据我了解,有效的模式是:
- 实例化所需服务(FooService)的 FooControllerFactory
- 带有构造函数的 FooController __construct(FooService $fooService)
- Controller 获取一些基本数据并从服务中获取结果
- 该服务包含所有必需的业务逻辑这是一个基础服务。最终,该服务将需要其他服务来进行各种活动。例如 CacheService、SomeOtherDataService。
问题是,包含/注入这些其他互连服务的有效/适当模式是什么?
我们目前已经非常简化了一个真实的例子:
拍卖控制器
/**
* get vehicles for specific auction
*/
public function getVehiclesAction ()
{
$auctionService = $this->getAuctionService(); // via service locator
$auctionID = (int) $this->params('auction-id');
$auction = $auctionService->getAuctionVehicle($auctionID);
return $auction->getVehicles();
}
拍卖服务
public function getAuctionVehicles($auctionID) {
$auction = $this->getAuction($auctionID);
// verify auction (active, permissions, ...)
if ($auction) {
$vehicleService = $this->getVehicleService(); // via service locator
$vehicleService->getVehicles($params); // $params = some various conditions or array of IDs
}
return false;
}
车辆服务
public function getVehicles($params) {
$cache = $this->getCache(); // via service locator
$vehicles = $cache->getItem($params);
if (!$vehicles) {
$vehicleDB = $this->getVehicleDB(); // via service locator
$vehicles = $vehicleDB->getVehicles($params);
}
return $vehicles;
}
建议的有效模式示例
拍卖控制器
public function __construct(AuctionService $auctionService) {
$this->auctionService = $auctionService;
}
/**
* get vehicles for specific auction
*/
public function getVehiclesAction ()
{
$auctionID = (int) $this->params('auction-id');
$auction = $this->auctionService->getAuctionVehicle($auctionID);
return $auction->getVehicles();
}
**AuctionService**
public function getAuctionVehicles($auctionID) {
$auction = $this->getAuction($auctionID); // no problem, local function
// verify auction (active, permissions, ...)
if ($auction) {
$vehicleService = $this->getVehicleService(); // we don't have service locator
$vehicleService->getVehicles($params); // $params = some various conditions or array of IDs
}
return false;
}
车辆服务
public function getVehicles($params) {
$cache = $this->getCache(); // we don't have service locator, but cache is probably static?
$vehicles = $cache->getItem($params);
if (!$vehicles) {
$vehicleDB = $this->getVehicleDB(); // where and how do we get this service
$vehicles = $vehicleDB->getVehicles($params);
}
return $vehicles;
}
一些注意事项:
- 服务仅在某些情况下相互连接,在 95% 的情况下它们是独立的
- 拍卖有很多不需要车辆的功能
- Vehicle 具有 VehicleController 和 VehicleService ,它们仅在某些情况下与 do Auction 相关,它是具有其他功能的独立模块
- 在控制器中注入所有需要的服务将浪费资源,因为并非每个操作都需要它们(在现实生活中的应用程序中,我们有更多互连的服务,而不仅仅是两个)
- 在多个服务中编写相同的业务逻辑只是为了避免使用服务定位器显然是一种无效的模式,是不可接受的。