Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to have DI container replace a global $registry object?

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.

like image 766
stefgosselin Avatar asked May 25 '11 09:05

stefgosselin


People also ask

How many dependencies should a class have?

The fact your class has so many dependencies indicates there are more than one responsibilities within the class. Often there is an implicit domain concept waiting to be made explicit by identifying it and making it into its own service. Generally speaking, most classes should never need more than 4-5 dependencies.

What is dependency injection container?

What is DI Container. A DI Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on the request and injects them when required. DI Container helps us to manage dependencies within the application in a simple and easy way.

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.


1 Answers

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

like image 183
Gérald Croës Avatar answered Oct 11 '22 03:10

Gérald Croës