10

I have started refactoring a small application to use a small DI container instead of having $registry::getstuff(); calls in my classes I inject them in a container.

This has raised 2 questions,

Q1 -> I extend Pimple DI class and create a container with dependencies specific to each object that will need DI. I then feed the object the whole shebang, and decrontruct it it in the constructor assigning the DI's objects to the class properties of the object I'm building.

Should I be separating the object in the new object() call? I just found it easier like this but seeing I'm a one man team right now I just want to confirm I have proper methodology.

Q2 -> I find the $registry object I was passing around all over will be uneeded if I do this on a few of the main classes, is this a normal result of using DI, no more registry? I may have a singleton or two injected in the container but it looks as that is all I will need and even those could easily be eliminitated since the DI has a share() property that returns the same instance of the object, effectively removing the need for singletons. Is this the way to rid an app of needing registry/singletons, because if it is it's darn easy like this.

hakre
  • 193,403
  • 52
  • 435
  • 836
Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65
  • *(tip)* [Inversion of Control Containers and the Dependency Injection pattern](http://www.martinfowler.com/articles/injection.html) – Gordon May 25 '11 at 09:41
  • Is your Q1 directed at the object creation code inside the anonymous Pimple function? If yes, then a code example might help to answer that question. – chiborg Jun 08 '11 at 12:25

1 Answers1

22

Q2 : If you were passing around all over your $registry object.... then your Registry was not really what is called a Registry (as Fowler described it).

A Registry is more or less a global object (a "well-known") with get/set methods. In PHP, two common prototypes for the implementations of a Registry would be

As a singleton

class RegistryAsSingleton
{
    public static function getInstance (){
       //the singleton part
    }

    public function getStuff ()
    {
       //some stuff accessed thanks to the registry
    }
}

With static methods all over the place

class RegistryAsStatic
{
    public static function getStuff()
    {
    }
}

Passing your Registry all over the place makes it, well, just an object: a container with no greater purpose than providing references to other objects.

Your DI container (using Pimple as you suggested in your OP) is kind of a Registry itself: It IS well known and enables you to get components from anywhere.

So yes, we can say that your DI container will remove the requirement and necessity of a registry by performing the same functionality.

BUT (there's always a but)

Registry are always guilty until proven innocent (Martin Fowler)

If you're using your DI Container to replace your Registry, this is probably wrong.

eg:

//probably a Wrong usage of Registry
class NeedsRegistry
{
    public function asAParameter(Registry $pRegistry)
    {
       //Wrong dependency on registry where dependency is on Connection
       $ct = $pRegistry->getConnection();
    }

    public function asDirectAccess ()
    {
       //same mistake, more obvious as we can't use another component
       $ct = Registry::getInstance()->getConnection();
    }
}

//probably a wrong replacement for Registry using DI Container
class NeedsContainer
{
    public function asAParameter(Container $pRegistry)
    {
       //We are dependent to the container with no needs, 
       //this code should be dependent on Connection
       $ct = $pContainer->getConnection();
    }

    public function asDirectAccess ()
    {
       //should not be dependent on container
       $ct = Container::getInstance()->getConnection();
    }
}

Why is this bad? Because your code is not less dependent than before, it still depends on a component (either a registry or a container) which does not provides a clear goal (we may think of interface here)

The Registry-pattern be useful in some cases because it's a simple and fairly inexpensive way to define components or data (e.g. global configuration).

A way to refactor the above example without relying on DI by removing the dependency would be:

class WasNeedingARegistry
{
    public function asAParameter (Connection $pConnection)
    {
       $pConnection->doStuff();//The real dependency here, we don't care for 
       //a global registry
    }
}

//the client code would be like
$wasNeedingARegistry = new WasNeedingARegistry();
$wasNeedingARegistry->setConnection($connection);

Of course, this may not be possible if the client code isn't aware of the connection, which is probably the reason why you probably ended using a Registry in the first place.

Now DI comes into play

Using DI makes our life better because it will handle the dependency and enables us to access the dependency in a ready-to-use state.

Somewhere in your code, you'll configure your components:

$container['connection'] = function ($container) {
    return new Connection('configuration');
};
$container['neededARegistry'] = function ($container) {
    $neededARegistry = new NeededARegistry();
    $neededARegistry->setConnection($container['connection']);
    return $neededARegistry;
};

Now you have everything you need to refactor your code:

// probably a better design pattern for using a Registry 
class NeededARegistry
{
    public function setConnection(Connection $pConnection)
    {
       $this->connection = $pConnection;
       return $this;
    }

    public function previouslyAsDirectAccess ()
    {
       $this->connection->doStuff();
    }
}

//and the client code just needs to know about the DI container
$container['neededARegistry']->previouslyAsDirectAccess();

The "client" code should be as isolated as possible. The client should be responsible for and inject its own dependencies (via set- methods). The client should not be responsible for handling its dependencies's dependencies.

class WrongClientCode
{
    private $connection;
    public function setConnection(Connection $pConnection)
    {
       $this->connection = $pConnection;
    }

    public function callService ()
    {
       //for the demo we use a factory here
       ServiceFactory::create('SomeId')
                       ->setConnection($this->connection)
                       ->call();
       //here, connection was propagated on the solely 
       // purpose of being passed to the Service
    }
}

class GoodClientCode
{
    private $service;
    public function setService(Service $pService)
    {
       //the only dependency is on Service, no more connection
       $this->service = $pService;
    }

    public function callService ()
    {
       $this->service->setConnection($this->connection)
                     ->call();
    }
}

The DI container will configure GoodClientCode with the Service that has already been properly configured with its Connection

As for the Singleton aspect, yes, it will enable you to get rid of them. Hope this helps

awei
  • 1,154
  • 10
  • 26
Gérald Croës
  • 3,799
  • 2
  • 18
  • 20
  • Hey. Thanks for your awesome feedback. YOu have made many points clearer, very much appreciated. – Stephane Gosselin Jun 08 '11 at 19:48
  • Very nice, thorough explanation. I'll definitely pass a link to this answer when my coworkers inevitably ask, "But can't we just pass in the container?" They are very fond of Zend's tendency to accept an array of "configuration parameters" which in many cases should be named parameters. – David Harkness Jun 20 '11 at 22:43
  • 2
    Great explanation. I love seeing bad code/good code examples on Stack. Quick question: where do you store the DI container in a typical MVC framework? Do you only have 1 that defines all your services/components? Or do you have many? – MikeMurko Aug 24 '12 at 16:26
  • Thanks for the explanation, I'm trying to make sense of DI Containers right now, and this has been a great help. – e_i_pi Jun 01 '16 at 01:45
  • Is this line really correct in the last class? ` $this->service->setConnection($this->connection)` Why does GoodClientCode have `this->connection`? – Olle Härstedt Jan 27 '20 at 22:19