如果单例是坏的,那么为什么服务容器是好的?

我们都知道 坏单身汉是什么样的,因为它们隐藏了依赖项和 其他原因

但是在一个框架中,可能有许多对象只需要实例化一次,并称为 来自世界各地(logger、 db 等)。

为了解决这个问题,我被告知使用一个所谓的“对象管理器”(或类似 symfony 的 服务容器) ,它在内部存储对服务(logger 等)的每个引用。

但是为什么一个服务提供商不像一个纯粹的 Singleton 那么糟糕呢?

服务提供者也隐藏了依赖关系,它们只是结束了第一个实例的创建。所以我真的很难理解为什么我们应该使用一个服务提供商而不是单一的。

我知道为了不隐藏依赖关系,我应该使用 DI (如 Misko 所说)

我想补充一点: 现在单例并不是那么邪恶,PHPUnit 的创建者在这里解释道:

DI + Singleton 解决了这个问题:

<?php
class Client {


public function doSomething(Singleton $singleton = NULL){


if ($singleton === NULL) {
$singleton = Singleton::getInstance();
}


// ...
}
}
?>

即使这并不能解决所有问题,这也很聪明。

除了 DI 和服务容器 有没有什么好的可以接受的解决方案访问这个帮助器对象?

20099 次浏览

The service locator pattern is an anti-pattern. It doesn't solve the problem of exposing dependencies (you can't tell from looking at the definition of a class what its dependencies are because they aren't being injected, instead they are being yanked out of the service locator).

So, your question is: why are service locators good? My answer is: they are not.

Avoid, avoid, avoid.

Because you can easily replace objects in Service Container by
1) inheritance (Object Manager class can be inherited and methods can be overriden)
2) changing configuration (in case with Symfony)

And, Singletons are bad not only because of high coupling, but because they are _Single_tons. It's wrong architecture for almost all kinds of objects.

With 'pure' DI (in constructors) you will pay very big price - all objects should be created before be passed in constructor. It will mean more used memory and less performance. Also, not always object can be just created and passed in constructor - chain of dependencies can be created... My English are not good enough to discuss about that completely, read about it in Symfony documentation.

Service Locator is just the lesser of two evils so to say. The "lesser" boiling down to these four differences (at least I can't think of any others right now):

Single Responsibility Principle

Service Container does not violate Single Responsibility Principle like Singleton does. Singletons mix object creation and business logic, while the Service Container is strictly responsible for managing the object lifecycles of your application. In that regard Service Container is better.

Coupling

Singletons are usually hardcoded into your application due to the static method calls, which leads to tight coupled and hard to mock dependencies in your code. The SL on the other hand is just one class and it can be injected. So while all your classed will depend on it, at least it is a loosely coupled dependency. So unless you implemented the ServiceLocator as a Singleton itself, that's somewhat better and also easier to test.

However, all classes using the ServiceLocator will now depend on the ServiceLocator, which is a form of coupling, too. This can be mitigated by using an interface for the ServiceLocator so you are not bound to a concrete ServiceLocator implementation but your classes will depend on the existence of some sort of Locator whereas not using a ServiceLocator at all increases reuse dramatically.

Hidden Dependencies

The problem of hiding dependencies very much exists forth though. When you just inject the locator to your consuming classes, you wont know any dependencies. But in contrast to the Singleton, the SL will usually instantiate all the dependencies needed behind the scenes. So when you fetch a Service, you dont end up like Misko Hevery in the CreditCard example, e.g. you dont have to instantiate all the depedencies of the dependencies by hand.

Fetching the dependencies from inside the instance is also violating Law of Demeter, which states that you should not dig into collaborators. An instance should only talk to its immediate collaborators. This is a problem with both Singleton and ServiceLocator.

Global State

The problem of Global State is also somewhat mitigated because when you instantiate a new Service Locator between tests all the previously created instances are deleted as well (unless you made the mistake and saved them in static attributes in the SL). That doesnt hold true for any global state in classes managed by the SL, of course.

Also see Fowler on Service Locator vs Dependency Injection for a much more in-depth discussion.


A note on your update and the linked article by Sebastian Bergmann on testing code that uses Singletons : Sebastian does, in no way, suggest that the proposed workaround makes using Singleons less of a problem. It is just one way to make code that otherwise would be impossible to test more testable. But it's still problematic code. In fact, he explicitly notes: "Just Because You Can, Does Not Mean You Should".

Service container hides dependencies as Singleton pattern do. You might want to suggest using dependency injection containers instead, as it has all the advantages of service container yet no (as far as I know) disadvantages that service container has.

As far as I understand it, the only difference between the two is that in service container, the service container is the object being injected (thus hiding dependencies), when you use DIC, the DIC injects the appropriate dependencies for you. The class being managed by the DIC is completely oblivious to the fact that it is managed by a DIC, thus you have less coupling, clear dependencies and happy unit tests.

This is a good question at SO explaining the difference of both: What's the difference between the Dependency Injection and Service Locator patterns?

For me, I try to avoid global constants, singletons for a simple reason, there are cases when I might need to APIs running.

For example, i have front-end and admin. Inside admin, I want them to be able to login as a user. Consider the code inside admin.

$frontend = new Frontend();
$frontend->auth->login($_GET['user']);
$frontend->redirect('/');

This may establish new database connection, new logger etc for the frontend initialization and check if user actually exists, valid etc. It also would use proper separate cookie and location services.

My idea of singleton is - You can't add same object inside parent twice. For instance

$logger1=$api->add('Logger');
$logger2=$api->add('Logger');

would leave you with a single instance and both variables pointing to it.

Finally if you want to use object oriented development, then work with objects, not with classes.