96

We all know how bad Singletons are because they hide dependencies and for other reasons.

But in a framework, there could be many objects that need to be instantiated only once and called from everywhere (logger, db etc).

To solve this problem I have been told to use a so called "Objects Manager" (or Service Container like symfony) that internally stores every reference to Services (logger etc).

But why isn't a Service Provider as bad as a pure Singleton?

Service provider hides dependencies too and they just wrap out the creation of the first istance. So I am really struggling to understand why we should use a service provider instead of singletons.

PS. I know that to not hide dependencies I should use DI (as stated by Misko)

Add

I would add: These days singletons aren't that evil, the creator of PHPUnit explained it here:

DI + Singleton solves the problem:

<?php
class Client {

    public function doSomething(Singleton $singleton = NULL){

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

        // ...
    }
}
?>

that's pretty smart even if this doesn't solve at all every problems.

Other than DI and Service Container are there any good acceptable solution to access this helper objects?

Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • 1
    who said that service container is good ? – tereško May 17 '11 at 18:30
  • @teresko: Many poeple. Symfony too: http://symfony.com/doc/current/book/service_container.html – dynamic May 17 '11 at 18:35
  • 2
    @yes Your edit is making false assumptions. Sebastian does, in no way, suggest that the code snippet is making 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". The correct solution would still be to not to use Singletons at all. – Gordon May 20 '11 at 12:06
  • @gordon: thanks for your input. At this point other than DI do you think there are a solution to this problem? – dynamic May 20 '11 at 15:42
  • 3
    @yes follow the SOLID principle. – Gordon May 20 '11 at 16:38
  • 2
    that wasnt meant as a joke at all. Follow [SOLID](https://secure.wikimedia.org/wikipedia/en/wiki/Solid_(object-oriented_design)) – Gordon May 22 '11 at 21:20
  • 22
    I dispute the assertion that singletons are bad. They can be misused, yes but so can _any_ tool. A scalpel can be used to save a life or end it. A chainsaw can clear forests to prevent bushfires or it can lop off a sizable portion of your arm if you don't know what you're doing. Learn to use your tools wisely and _don't_ treat advice as gospel - that way lies the unthinking mind. – paxdiablo May 23 '11 at 04:16
  • 6
    @paxdiablo but they *are* bad. Singletons violate SRP, OCP and DIP. They introduce global state and tight coupling into your application and will make your API lie about it's dependencies. All this will negatively affect maintainability, readability and testability of your code. There might be rare cases where these drawbacks outweigh the little benefits, but I would argue that in 99% you dont need a Singleton. Especially in PHP where Singletons are only unique for the Request anyways and it's dirt simple to assemble collaborator graphs from a Builder. – Gordon May 23 '11 at 16:59
  • 1
    @paxdiablo: Singletons are not a tool. Your analogy was flawed from the beginning. – jason Jun 07 '11 at 14:12
  • 5
    No, I don't believe so. A tool is a means to carry out a function, usually by making it easier somehow, although some (emacs?) have the rare distinction of making it harder :-) In this, a singleton is no different to a balanced tree or a compiler. If you need to ensure only one copy of a object, a singleton does this. Whether it does it _well_ can be debated but I don't believe you can argue that it doesn't do it at all. And there may be better ways, such as a chainsaw being faster than a handsaw, or a nailgun vs. a hammer. That doesn't make the handsaw/hammer less of a tool. – paxdiablo Jun 08 '11 at 01:45

5 Answers5

81

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".

bwoebi
  • 23,637
  • 5
  • 58
  • 79
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 1
    Especially the testability should be enforced here. You can not mock static method calls. You can however mock services that were injected through constructor or setter. – David May 18 '19 at 20:25
43

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.

jason
  • 236,483
  • 35
  • 423
  • 525
  • Thanks I got this point (otherwise I wouldn't opened this question) But i don't get why other people keep saying to solve singleton issue use a service container (and these people seems professional) – dynamic May 17 '11 at 17:39
  • 1
    That's what it seemed to me as well. I think real dependency injection would be the way to go, but coming from Java I haven't found a really good DI framework for PHP. – Daff May 17 '11 at 17:40
  • 6
    Looks like you don't know nothing about interfaces. Class just describes necessary interface in constructor signature - and it's all what he need to know. Passed Service Locator should implement interface, that's all. And if IDE will check implementation of interface, it's will be pretty easy to control any changes. – OZ_ May 17 '11 at 17:42
  • 4
    @yes123: People that say that are wrong, and they are wrong because SL is an anti-pattern. Your question is "why are SL good?" My answer is: they are not. – jason May 17 '11 at 18:51
  • 5
    I won't argue if SL is an anit-pattern or not, but what I will say is it's very much a lesser of evils when compared to singleton and globals. You can't test a class that depends upon a singleton, but you definitely can test a class that depends on a SL (albiet you can screw up the SL design to the point where it doesn't work)... So that's worth noting... – ircmaxell May 17 '11 at 19:29
  • 1
    @OZ_: I think you're missing the point. If I have `class Foo { public Foo(IServiceLocator serviceLocator) { } }` I can NOT tell what `Foo` is dependent on. I know it's dependent on `IServiceLocator` but I don't know what it's doing with any `IServiceLocator` that is passed in. For all I know, `Foo` could be dependent on every service that `IServiceLocator` is able to locate. If `Foo` uses an `IServiceLocator` I have no idea what `Foo` is really dependent on. – jason Sep 17 '11 at 12:25
  • 3
    @Jason you need to pass object which implements Interface - and it's only what you need to know. You are limiting yourself by only definition of class constructor and want to write in constructor all classes (not interfaces) - it's stupid idea. All you need is Interface. You can successfully test this class with mocks, you can easily change behavior without changing code, there is no extra dependencies and coupling - that's all (in general) what we want to have in Dependency Injection. – OZ_ Sep 17 '11 at 13:48
  • 1
    So, what is the alternative if your object depends on 10 or 15 other independent objects? That would make a pretty ugly construct function if you have to pass them as arguments one by one. – Mahn Jun 27 '12 at 20:45
  • @Mahn: That's a code smell that has nothing to do with DI. Just aggregate constructor parameters into objects themselves. – jason Jun 28 '12 at 13:19
  • 3
    Sure, I'll just throw together Database, Logger, Disk, Template, Cache and User into a single "Input" object, surely it will be easier to tell which dependencies does my object rely on than if I had used a container. – Mahn Jun 28 '12 at 15:21
  • 2
    And I'm not saying that a single object should handle both Database and Templating stuff, but my point is, it *can* happen an object relies on several independent objects, where aggregating them together in another object makes no sense. – Mahn Jun 28 '12 at 15:27
  • @Mahn: Don't be silly, I didn't say lump them all into one. You're arguing against a straw man. – jason Jun 28 '12 at 17:30
  • @Daff Try [symfony/DependencyInjection](http://symfony.com/doc/2.1/components/dependency_injection/introduction.html) or Pimple maybe? – Adam Apr 10 '13 at 16:19
  • This answer is pretty pointless because it lacks an argument and just blames the pattern as being "bad" without giving a proper reason or background with an example. Even this article from Martin Fowler doesn't tell you "A is good and B is bad". https://martinfowler.com/articles/injection.html – floriank May 25 '18 at 22:16
  • @jason you can have SL implemented also in an autowired way, so it's close(r) (or a combination) to dependency injection, yet you don't have to pass and construct dependencies as in DI what does ServiceLocator implicitly.Other "only" bad difference to DI is that with DI you see dependencies inside signature while inside autowire-less SL you can see calls scattered to SL anywhere inside a class body.Therefore also the most common approach in frameworks is sort of combination of DI via auto wiring with services definitions as in ServiceLocator.Alongside they often still provide direct SL access – FantomX1 Sep 01 '20 at 09:52
4

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?

Community
  • 1
  • 1
rickchristie
  • 1,640
  • 1
  • 17
  • 29
  • "the DIC injects the appropriate dependencies for you" Doesn't this happens with Singleton too? – dynamic May 17 '11 at 18:27
  • 5
    @yes123 - If you're using a Singleton, you wouldn't inject it, most of the times you'd just access it globally (that's the point of Singleton). I suppose if you say that if you *inject* the Singleton, it will not hide dependencies, but it kind of defeats the original purpose of the Singleton pattern - you would ask yourself, if I don't need this class to be accessed globally, why do I need to make it Singleton? – rickchristie May 17 '11 at 18:32
2

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.

OZ_
  • 12,492
  • 7
  • 50
  • 68
0

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.

romaninsh
  • 10,606
  • 4
  • 50
  • 70
  • 1
    so your method is to pass the `$api ` var around your framework? I didn't exactly get what you mean. Also if the call `add('Logger')` returns the same instance basically you have a service cotainer – dynamic May 20 '11 at 15:29
  • yeah, that's right. I refer to them as "System Controller" and they are meant to enhance functionality of API. In a similar way adding "Auditable" controller to a model twice would work in exactly same way - create only one instance and only one set of audit fields. – romaninsh May 21 '11 at 21:09