Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

People say Service Locators are bad because they expose the dependencies in some random method from the class (and not in the constructor's arguments like it should):

class A{

function F(){

instead of

class A{
protected $db; 

function __construct(DB $db){
  $this->db = $db;

function F(){

But consider a function, like imagejpeg() from GD. Obviously you can't "inject" that, so you have to call it somewhere in your class, just like your service. So isn't this the same thing? That function is a dependency too.

Or what about instantiating an object somehwere in your class methods, like PDO. Aren't these things exactly like services after all? So why all the fuss about service locators being evil?

share|improve this question
why close this question? – Dipan Mehta Mar 3 '12 at 14:35
@Dipan - Not constructive - This question is not a good fit to our Q&A format. We expect answers to generally involve facts, references, or specific expertise; this question will likely solicit opinion, debate, arguments, polling, or extended discussion.. The question is asked with a lot of bias. She's making the assumption that service locators are bad. It's clear where she stands on the issue, and that's not what we're looking for in questions. – jmort253 Mar 3 '12 at 19:01
up vote 3 down vote accepted

The reason service locators are evil is because your class really should not be concered with any of the details of how to instantiate it's dependencies. You will end up with classes that know way too much about way too many things are get very hard to separate. Moreover, when you need to swap out that database class it is strewn about dozens of files in dozens of places rather than in a few initialization statements.

In the case of GD* functions, the way to manage that is to build an some sort of adapter interface and class that deals with calling GD* directly. Your classes talk to this interface which can easily be swapped and mocked out as you need. And need not actually be fully implemented when you are writing your main line of business code.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.