從my question on service locators開始,我決定改用構造函數注入。請考慮下面的代碼:這是構造器注入的一個理智的實現嗎?
<?php
interface IAppServiceRegistry {
public function getDb();
public function getLogger();
}
interface IFooServiceRegistry extends IAppServiceRegistry {
public function getFooBarBazModel();
}
class AppServiceRegistry
implements IAppServiceRegistry, IFooServiceRegistry
{
private $logger;
private $db;
private $fooBarBazModel;
public function getDb() {
// return db (instantiate if first call)
}
public function getLogger() {
// return logger (instantiate if first call)
}
public function getFooBarBazModel() {
if (!isset($this->fooBarBazModel)) {
$this->fooBarBazModel = new FooBarBazModel($this->getDb());
}
return $this->fooBarBazModel;
}
}
// Example client classes:
/**
* Depends on db, logger and foomodel.
*/
class Foo {
private $db;
private $logger;
private $fooModel;
public function __construct(IFooServiceRegistry $services) {
$this->db = $services->getDb();
$this->logger = $services->getLogger();
$this->fooModel = $services->getFooModel();
}
}
/**
* Depends on only db and logger.
*/
class BarBaz {
private $db;
private $logger;
public function __construct(IAppServiceRegistry $services) {
$this->db = $services->getDb();
$this->logger = $services->getLogger();
}
}
然後我會添加新的服務工廠的方法來對註冊表的應用演變,只要創造適當的邏輯分離的接口。
這種方法是否理智?
我感覺有些東西聞起來很糟糕,但是讓我沿着這條路走下去的是「什麼時候課程取決於5或6種不同的模型,再加上記錄器等?」。但是我應該記住1.YAGNI和2.正如你所指出的,也許我的設計需要再次關注這一點,可能會違反SRP。謝謝您的幫助! – oops
@MarkSeemann如何將ServicesProvider objet作爲單例讓您可以訪問2個或3個服務對象?它在哪裏破壞SRP?我的意思是ServicesProvider做一件事就是提供服務對象。 – Rushino
當談到DI時,單身人士相當成問題:http://stackoverflow.com/questions/1917180/di-and-singleton-pattern-in-one-implementation/1917230#1917230 –