Following on from my question on service locators I have decided to use constructor injection instead. Please consider the following code:
<?php
interface IAppServiceRegistry {
public function getDb();
public function getLogger();
}
interface IFooServiceRegistry extends IAppServiceRegistry {
public function getFooBarBazModel();
}
class AppServiceRegistry
implements IAppServiceRegistry, IFooServiceRegistry
{
private $logger;
private $db;
private $fooBarBazModel;
public function getDb() {
// return db (instantiate if first call)
}
public function getLogger() {
// return logger (instantiate if first call)
}
public function getFooBarBazModel() {
if (!isset($this->fooBarBazModel)) {
$this->fooBarBazModel = new FooBarBazModel( $this->getDb() );
}
return $this->fooBarBazModel;
}
}
// Example client classes:
/**
* Depends on db, logger and foomodel.
*/
class Foo {
private $db;
private $logger;
private $fooModel;
public function __construct(IFooServiceRegistry $services) {
$this->db = $services->getDb();
$this->logger = $services->getLogger();
$this->fooModel = $services->getFooModel();
}
}
/**
* Depends on only db and logger.
*/
class BarBaz {
private $db;
private $logger;
public function __construct(IAppServiceRegistry $services) {
$this->db = $services->getDb();
$this->logger = $services->getLogger();
}
}
Then I would add new service factory methods to the registry as the application evolved, creating segregated interfaces wherever logically appropriate.
Is this approach sane?
Although I don't normally read php, I think I understand most of it. Technically, it looks fine, but then you write
I would add new service factory methods to the registry as the application evolved
That tends to hurt the idea of loose coupling because instead of a general-purpose Service Locator you now have a specialized Service Locator.
Injecting such a serivce registry into each class works against the Single Responsibility Principle (SRP) because once a class has access to the registry, it is too easy to request yet another dependency than originally conceived, and you will end up with a God Object.
It would be better to inject the required dependencies directly into the classes that need them. Thus, your Foo class' constructor should take a db, a logger and a fooModel, while the BarBaz class should take only a db and a logger parameter.
The next question may then be: What if I need a lot of different dependencies to perform the work? That would require a truly ugly constructor with lots of parameters, and this goes against other well-known OO practices.
True, but if you need lots of dependencies, you are probably violating the SRP and should try to split your design into finer-grained objects :)
This implementation is almost the same as the service locator you previously showed us.
A good question to ask is whether upon looking at the class of your objects, you know everything about the objects needs to get their job done. In your case you still don't know.
If Foo needs the db, logger and model, you make this clear by asking for these in the constructor.
Here's a good read on the matter:
http://misko.hevery.com/code-reviewers-guide/flaw-digging-into-collaborators/
I've been grappling with this kind of problem lately. Service Locator vs Depedency Injection.
I agree with Mark that the way to go is to inject individual fine-grained objects into the constructor, as required. The only drawback, as Mark has highlighted, is that when you build a complex object graph, you inevitably have to start somewhere. This means that your high-level objects will have lots of services (objects) injected into them.
The easy way round this is to use something to do the hard work for you. The prime example of this is Google's Guice which seems to me a very good way of going about things. Sadly it's written for Java! There are PHP versions about; I'm not sure any of them quite measure up to Guice at this point.
I've written a post on this topic which goes into more detail; which you may find interesting. It includes a simple implementation of a dependency injection framework.
The bottom line is that if you've got a class Foo with a number of requirements, you can create your class as such:
/**
* Depends on db, logger and foomodel.
*/
class Foo
{
private $db;
private $logger;
private $fooModel;
/**
* (other documentation here)
* #inject
*/
public function __construct(IDbService $db, ILoggerService $logger, $iModelService $model)
{
// do something
}
}
When you want a new Foo object, you simply ask the dependency injection framework to create you one:
$foo = $serviceInjector->getInstance('Foo');
The dependency injector will do the hard work, making sure it injects the dependencies. This includes any dependencies of the dependencies, if that makes sense. In other words it will sort it all out recursively up the tree.
Later, when you find you need an IBarService object, you can just add it to the Construtor, without altering any other code!
Related
I've been reading about Dependency Injection but the examples I've found just look like bad code to me, so my main question is am I right in thinking it is bad code, or am I misunderstanding the purpose of it, and is my example any better?
class Photo {
protected $db;
public function __construct()
{
$this->db = DB::getInstance();
}
}
So this is bad code, and the suggestion of Dependency Injection, due to the multitude of setters that might be created if we explicitly set every variable, is:
class Container {
protected $db;
public static newPhoto()
{
$photo = new Photo;
$photo->setDB(static::$db);
$photo->setConfig();
$photo->setResponse();
return $photo;
}
}
$photo = Container::newPhoto();
But correct me if I'm wrong, we've just built a class whose sole responsibility it is to build another class, seems quite pointless, and we are using static methods which is apparently a very bad idea.
The one benefit that I do see, which surprisingly to me isn't mentioned is that we can now test the Photo class independently by using the setters, whilst in the first example we couldn't.
Something like this makes more sense to me:
class Photo {
protected $db;
protected $config;
protected $response;
public function __construct($dbConn=null,$config='123',$response=true)
{
if(is_null($dbConn))
$this->db = DB::getInstance();
else
$this->db = $dbConn;
...etc
}
}
$photo = new Photo($dbConn);
The class builds itself, there is no need for the static method to actually be called, the class can be tested with dummy data if values are used otherwise it falls back on defaults (which seems to be the only point of the Container class), and the dependencies are still somewhat obvious as opposed to the Container.
The goal of Dependency Injection pattern is to decouple how objects that work together are constructed. In your example, it is not the concern of the Photo class to know how to construct a DB instance, but only to use a DB instance to achieve its goals.
The obvious advantage that you already noticed is in testing where you can easily pass mock DB instance if you want to test just the Photo functionality. But you can think also about connection pooling for example where a container has a pool of DB instances and pass one of them to your Photo object for doing its work. When the Photo life-cycle ends the DB instance is returned to the pool and used elsewhere.
The implementation of this pattern can be achieved using constructors with arguments, setters, annotations (at least in Java) and even XML configuration files. In the case of annotations or XML configuration files a container will parse that information create the appropriate needed objects and inject them in the client class.
What you describe at C1 and C2 is a factory class that exposes static methods for obtaining Photo instances. This is a very common pattern used in many places in Java.
I don't know where you leaned about the DI, but the resources seem quite questionable. Instead you should begin by watching this lecture, followed by article from Martin Fowler. Maybe supplemented by this short video.
class Container {
protected $db;
public static newPhoto()
{
$photo = new Photo;
$photo->setDB(static::$db);
$photo->setConfig();
$photo->setResponse();
return $photo;
}
}
$photo = Container::newPhoto();
This is not implementing dependency injection. It actually is just an example of poorly implemented static factory method (anti)pattern. Especially the magical methods $photo->setConfig() and $photo->setResponse() which apparently do some work, but receive no parameters.
And then there is this code:
class Photo {
protected $db;
protected $config;
protected $response;
public function __construct($dbConn=null,$config='123',$response=true)
{
if(is_null($dbConn))
$this->db = DB::getInstance();
else
$this->db = $dbConn;
...etc
}
}
$photo = new Photo($dbConn);
Instead of just assigning values, you decide to hide the dependencies of it, and, if they are not provided, to take them from global scope. And of course, your constructor ends up containing quite a log of computation. Thus making it untestable.
Oh .. and then there is the magical boolean value. Whenever where is such a parameter assigned to a class in constructor, it is a clear sign that you actually needed two different classes, which implement same interface.
So.. to answer your question:
I've been reading about Dependency Injection but the examples I've found just look like bad code to me, so my main question is am I right in thinking it is bad code, or am I misunderstanding the purpose of it, and is my example any better?
No. Your example is not better. You just combined the worst parts from both your earlier code example in single class definition.
With regards to using class objects within another class what is the best practice? To pass the class objects in the class _construct statement or create a new class object?
Example 1:
class Foo {
private $bar;
public function __construct($bar){
$this->bar = $bar;
}
}
Or Example 2 :
class Foo {
private $bar;
public function __construct(){
$this->bar= NEW bar;
}
}
I'm aware that obviously it's taken for granted that the class file must already be included somewhere else, and in the first instance a class object of this type would need to exist already, but I want to know what the advantages are each method are, as I have a lot of classes I need to code that use a database object and I need the best way to pass this into the classes. Is there a third option that's better than these two?
From what I can understand, the advantage of the first one could be a few less lines of coding and in the case of a DB, not having a new connection created. The second one might be better however because it's more self contained? Anyhow I thought I'd ask the experts.
The first. (This approach is called Dependency Injection).
The constructor asks for whatever the object in questions needs in order to work. This way, it's pretty clear from the methods alone (what they need, and what they return), what it does. Without even looking at the source code.
A way to improve your code would be to introduce type hinting into your method:
class Foo {
private $bar;
public function __construct(Bar $bar){
$this->bar = $bar;
}
}
So that only Bar objects may be passed in.
Advantages of Dependency Injection
Very readable.
Ability to tell the method's dependencies without viewing the source code.
Makes Unit Testing possible.
*Saves kittens from God's wrath.
* Disclaimer: No kittens were harmed during the manifestation of this answer
You should go for option 1, as this is the simplest form of dependency injection.
In option 1:
classes are independent of each other
classes can be tested independent, using a mock for the bar class
In general, I'd chime in with the DI crowd for reasons outlined in How to Think About the “new” Operator with Respect to Unit Testing:
But the reason why Dependency Injection is so important is that within unit-tests you want to test a small subset of your application. The requirement is that you can construct that small subset of the application independently of the whole system. If you mix application logic with graph construction (the new operator) unit-testing becomes impossible for anything but the leaf nodes in your application.
Separating your code into creator graphs and collaborator graphs will help to keep your code maintainable and testable. Even better, code against interfaces and it will be very easy to swap out concrete implementations against other ones. This makes changing your code simple, because you don't have to wade through your code hunting for hardcoded dependencies.
For instance, assuming your Bar requires a Logger, you'd do
class Foo
{
private $logger;
public function __construct(LogInterface $logger)
{
$this->logger = $logger;
}
}
And then you pass in any concrete implementation implementing that LogInterface, like a Database Logger or a StdOutLogger or maybe a Composite Logger holding both of these. Another example would be a Database object. You can create that once in your bootstrap and then pass it to the objects making use of it.
When in doubt, go with Dependency Injection.
However, you don't always have to inject stuff. It depends whether the object (your Bar) is an Injectable or a Newable. To quote Misko Hevery:
An Injectable class can ask for other Injectables in its constructor. […] Injectables tend to have interfaces since chances are we may have to replace them with an implementation friendly to testing. However, Injectable can never ask for a non-Injectable (Newable) in its constructor. This is because DI framework does not know how to produce a Newable. […] Some examples of Newables are: Email, MailMessage, User, CreditCard, Song. If you keep this distinctions your code will be easy to test and work with. If you break this rule your code will be hard to test.
In a nutshell, when you have something that cannot be reasonably injected, because it is based on user-supplied or runtime information, you can new it. This is especially true for Value Objects and Data Types:
class Foo
{
private $storage;
public function __construct()
{
$this->storage = new SplObjectStorage;
}
}
There is no point in injecting SplObjectStorage. It's just a data type.
Others have already answered your question - definitely go with the first approach, which uses Dependency Injection.
I just wanted to chip in with another popular alternative you may not be aware of: using a Dependency Injection Container.
A great, simple example of this is Pimple; developed by Fabien Potencier, the man behind the Symfony frameworks.
Example 3:
# In a bootstrap file...
require_once '/path/to/Pimple.php';
$container = new Pimple();
$container['bar'] = function ($c) {
return new Bar(/** If bar has dependencies, put them here **/);
};
$container['foo'] = function ($c) {
return new Foo($c['bar']);
};
# You'd still inject the service using DI, because it's not good
# practice for your objects to rely directly on the container
class Foo {
private $bar;
public function __construct($bar){
$this->bar = $bar;
}
}
# The difference would be how you call Foo...
$foo = $container['foo'];
# So now your code doesn't need to know about the dependencies, and it's easy
# to change them at any time by making a single change in your configuration
Symfony2 uses a more robust Container, which is also available as a standalone compenent. But Pimple is probably your best bet unless you're developing a large-scale application.
I'd say use the 1st option. While doing so, I'd say programming to abstractions is a better idea than programming to an implementation.
Your first option is a form of aggregation while the second is that of composition. The benefit you would get with abstractions is that your client class that uses class FOO will be able to get FOO to do some activity based on a particular implementation of the interface it decides to send into the constructor..
A C# example below
class Foo {
private IBar bar;
public Foo(IBar obj){
this.bar = obj;
}
public void myFooMethod()
{
bar.ExecuteMethod();
}
}
The class calling FOO
public class MyCallingClass
{
public void CallFooMethod()
{
IBar bar1Obj = new BAR1();
Foo fooObject = new Foo(bar1Obj);
fooObject.ExecuteMethod();
//or
IBar bar2Obj = new BAR2();
fooObject = new Foo(bar2Obj);
fooObject.ExecuteMethod();
//or
IBar bar3Obj = new BAR3();
fooObject = new Foo(bar3Obj);
fooObject.ExecuteMethod();
}
}
Now my calling class can pass any implementation of IBar to the FOO class.
Hope this helped.
Ok, Dependency Injection is wonderful, and helpful and saves kittens, so I'm not going to discuss it in detail.
Instead, I'm going to suggest you implement both solutions:
class Foo {
private $bar;
public function __construct($bar = null){
$this->bar = isset($bar) ? $bar : new Bar();
}
}
That way, you can use the default class by default, and if you need to change the functionality, you can do that too.
I'm new to OOP and thought I'd give Silex a try on a small app I'm attempting. I'm looking for some advice as to whether my design falls in line with good object oriented principles.
I have a User object which is basically just a bunch of properties, getters and setters. I then have a UserService object which will contain the logic for authenticating users, getting a user from the database, setting or updating user information, etc. I also have a UserServiceProvder class which is there to provide an instance of the UserService class to the app (which seems to be the best way to create a reusable chunk of code in Silex).
The question I have now is this: I am using the Doctrine DBAL that ships with Silex and when I instantiate the UserService class, I'm tempted to pass in a reference to the Doctrine object and then hard code calls to that object into methods of the UserService class.
For instance, to return a User from the database by id, I might create a method called getUserById($id) and then hardcode a Doctrine prepared statement into that method to select that user from the database and then return a User object.
Would it be better for me to create a whole other service that is just a further abstraction of the Doctrine DBAL and pass that to UserService when I instantiate it? That way, I could hard code the Doctrine prepared statements into that class, leaving my UserService class more encapsulated and reusable in case I decide to move away from Doctrine in the future.
I guess what I'm having a hard time with is realizing if there is a such a thing as overkill in OOP. It seems to me like the second method is much more reusable, but is it necessary or wise?
Moving the Database access to a separate class will bring you a couple of advantages. First of all, if you keep the database access apart from the rest of your logic you can replace the implementation of your database access more easy. If for a reason you want to drop the Doctrine DBAL you'll be happy that all the code is just referencing some interface to a repository instead of directly querying a database.
A second great advantage is that you can test your application logic in separation of your database access logic. If you inject a Repository for users inside your UserService you can Mock this in your tests and be sure they only fail if something is wrong with the actual application logic.
A small example of what you could do
The interface is convenient for reference throughout your codebase. No code references the implementation, only the interface. That way you can easily replace the implementation of the interface without touching all the places it is used:
interface IUserRepository
{
/**
* #return User
*/
public function getUserById($userId);
}
Of course you do need an implementation of said interface. This is what you inject into your UserService. This is what you one day might replace with another implementation of the interface:
class DoctrineDBALUserRepository implements IUserRepository
{
/**
* #return User
*/
public function getUserById($userId)
{
//implementation specific for Doctrine DBAL
}
}
The UserService only knows about the interface and can use it freely. To avoid having to inject the UserRepository in a lot of places in your code you could create a convenience build method. Notice the constructor that references the interface and the build method that injects an implementation of that interface:
class UserService
{
private $UserRepository;
public static build()
{
return new UserService(new DoctrineDBALUserRepository());
}
public function __construct(IUserRepository $UserRepository)
{
$this->UserRepository = $UserRepository;
}
public function getUserById($userId)
{
if ($User = $this->UserRepository->getUserById($userId) {
return $User;
}
throw new RuntimeException('O noes, we messed up');
}
With this in place you can write tests for the business logic (e.g. throw an exception if saving fails):
public function UserServiceTest extends PHPUnit_Framework_TestCase
{
public function testGetUserById_whenRetrievingFails_shouldThrowAnException()
{
$RepositoryStub = $this->getMock('IUserRepository');
$RepositoryStub->expects($this->any())->method('getUserById')->will($this->returnValue(false);
$UserService = new UserService($RepositoryStub);
$this->setExpectedException('RuntimeException');
$UserService->getUserById(1);
}
}
I can imagine you're not familiar with the last bit of code if you're not into unit-testing yet. I hope you are and if not urge you to read up on that as well :D I figured it was good for the completeness of the answer to include it no matter what.
I'm trying to get my head around Dependency Injection and I understand it, for the most part.
However, say if, for some reason, one of my classes was dependent on several classes, instead of passing all of these to this one class in the constructor, is there a better, more sensible method?
I've heard about DI Containers, is this how I would go about solving this problem? Where should I start with this solution? Do I pass the dependencies to my DIC, and then pass this to the class that needs these dependencies?
Any help that would point me in the right direction would be fantastic.
Dependency Injection !== DIC
People should really stop confusing them. Dependency Injection is idea that comes from Dependency Inversion principle.
The DIC is "magic cure", which promises to let you use dependency injection, but in PHP is usually implemented by breaking every other principle of object oriented programming. The worst implementations tend to also attach it all to global state, via static Registry or Singleton.
Anyway, if your class depends on too many other classes, then in general , it signifies a design flaw in the class itself. You basically have a class with too many reasons to change, thus, breaking the Single Responsibility principle.
In this case, then dependency injection container will only hide the underlaying design issues.
If you want to learn more about Dependency Injection, i would recommend for you to watch the "Clean Code Talks" on youtube:
The Clean Code Talks - Don't Look For Things!
The Clean Code Talks - "Global State and Singletons"
If you have several dependencies to deal with, then yes a DI container can be the solution.
The DI container can be an object or array constructed of the various dependent object you need, which gets passed to the constructor and unpacked.
Suppose you needed a config object, a database connection, and a client info object passed to each of your classes. You can create an array which holds them:
// Assume each is created or accessed as a singleton, however needed...
// This may be created globally at the top of your script, and passed into each newly
// instantiated class
$di_container = array(
'config' = new Config(),
'db' = new DB($user, $pass, $db, $whatever),
'client' = new ClientInfo($clientid)
);
And your class constructors accept the DI container as a parameter:
class SomeClass {
private $config;
private $db;
private $client;
public function __construct(&$di_container) {
$this->config = $di_container['config'];
$this->db = $di_container['db'];
$this->client = $di_container['client'];
}
}
Instead of an array as I did above (which is simple), you might also create the DI container as an class itself and instantiate it with the component classes injected into it individually. One benefit to using an object instead of an array is that by default it will be passed by reference into the classes using it, while an array is passed by value (though objects inside the array are still references).
Edit
There are some ways in which an object is more flexible than an array, although more complicated to code initially.
The container object may also create/instantiate the contained classes in its constructor as well (rather than creating them outside and passing them in). This can save you some coding on each script that uses it, as you only need to instantiate one object (which itself instantiates several others).
Class DIContainer {
public $config;
public $db;
public $client;
// The DI container can build its own member objects
public function __construct($params....) {
$this->config = new Config();
// These vars might be passed in the constructor, or could be constants, or something else
$this->db = new DB($user, $pass, $db, $whatever);
// Same here - the var may come from the constructor, $_SESSION, or somewhere else
$this->client = new ClientInfo($clientid);
}
}
I've wrote an article about this problem.
The ideea is to use a combination of abstract factory and dependency injection to achieve transparent dependency resolving of (possible nested) dependencies. I will copy/paste here the main code snippets:
namespace Gica\Interfaces\Dependency;
interface AbstractFactory
{
public function createObject($objectClass, $constructorArguments = []);
}
The abstract factory implementation is:
namespace Gica\Dependency;
class AbstractFactory implements \Gica\Interfaces\Dependency\AbstractFactory, \Gica\Interfaces\Dependency\WithDependencyInjector
{
use WithDependencyInjector;
/**
* #param string $objectClass
* #param array $constructorArguments
* #return object instanceof $class
*/
public function createObject($objectClass, $constructorArguments = [])
{
$instance = new $objectClass(...$constructorArguments);
$this->getDependencyInjector()->resolveDependencies($instance);
return $instance;
}
}
The dependency injector is this:
namespace Gica\Dependency;
class DependencyInjector implements \Gica\Interfaces\Dependency\DependencyInjector
{
use \Gica\Traits\WithDependencyContainer;
public function resolveDependencies($instance)
{
$sm = $this->getDependencyInjectionContainer();
if ($instance instanceof \Gica\Interfaces\WithAuthenticator) {
$instance->setAuthenticator($sm->get(\Gica\Interfaces\Authentication\Authenticator::class));
}
if ($instance instanceof \Gica\Interfaces\WithPdo) {
$instance->setPdo($sm->get(\Gica\SqlQuery\Connection::class));
}
if ($instance instanceof \Gica\Interfaces\Dependency\WithAbstractFactory) {
$instance->setAbstractFactory($sm->get(\Gica\Interfaces\Dependency\AbstractFactory::class));
}
//... all the dependency declaring interfaces go below
}
}
The dependency container is the standard one.
The client code could look something like this:
$abstractFactory = $container->get(\Gica\Interfaces\Dependency\AbstractFactory::class);
$someHelper = $abstractFactory->createObject(\Web\Helper\SomeHelper::class);
echo $someHelper->helpAction();
Notice that dependencies are hidden, and we can focus on the main bussiness. My client code doesn't care or know that $someHelper need an Authenticator or that helpAction need an SomeObject to do its work;
In the background a lot of things happen, a lot of dependencies are detected, resolved and injected.
Notice that I don't use the new operator to create $someObject. The responsability of actual creation of the object is passed to the AbstractFactory
P.S. Gica is my nickname :)
I recommend you to use Singltones or Mutlitones. In these cases you will be always able to get objects via static class' methods.
The other way (couldn't find a correct pattern name, but it could be Registry) is to use one global static object to store multiple objects' instances. E.g. (simplified code, without any checks):
class Registry {
private static $instances = array();
public static function add($k, $v) {
$this->instances[$k] = $v;
}
public static function get($k) {
return $this->instances[$k];
}
}
class MyClass {
public function __construct() {
Registry::add('myclass', $this);
}
}
i don´t have a lot of php experience i'd need some help,
i have a php MVC framework,
i use this class:
class Registry {
private $objects;
private $settings;
public function __construct() {
}
public function iniObject($class, $key)
{
$this->objects[ $key ] = new $class( $this );
}
public function getObject( $key )
{
return $this->objects[ $key ];
}
public function storeSetting( $setting, $key )
{
$this->settings[ $key ] = $setting;
}
public function getSetting( $key )
{
return $this->settings[ $key ];
}
}
then i pass the registry to the other classes like:
Class Controller
{
/*
* #registry object
*/
protected $registry;
function __construct(Registry $registry)
{
$this->registry = $registry;
//i can use any class from my registry class like the logger class below
$this->registry->getObject('log')->write_log('debug', "Controller Class Initialized");
}
/**
* #all controllers must contain an index method
*/
public function index() {}
}
i start my bootstrap.php with
$registry = new Registry();
// Instantiate some classes
$registry->iniObject( 'Utf8', 'utf8');
$registry->iniObject( 'Uri', 'uri');
$registry->iniObject( 'Router', 'router');
i get any method like:
$registry->getObject('router')->_set_routing();
and i get a view like:
$registry->getObject('output')->_display('myview');
in this way i can use all the classes inside other classes
passing the registry class like DI constructor, works well,
few code and fast execution,
i've been reading about DI containers and other things,
i'd like to know a better ways to do this, if the registry gets
bigger and bigger how will affect the framework i mean i pass
all the registry to every class, there´s a way to pass just
dependencies that every class needs instead the full registry,
is the registry the best way to work with objects cos allow me
to use any class inside any other class or you thing this isn´t a good
way to do it, any recommendation about DI containers libraries,
please i'd like to recieve ideas from more experienced php
programmers to do this
thanks a lot
While I am not an expert, I am currently using the yadif DI framework in my project (https://github.com/beberlei/yadif). I have modified it slightly to suit my purposes.
While the dependency injection and the registry object allows you to access an object from anywhere, I believe the difference is that in dependency injection, the dependecy object is instantiated and passed into the requiring object when it is instantiated.
This passing in can be done via the constructor or by setting properties of the requiring object.
The main point is then that the requiring object and its dependencies are loosely coupled.
As a quick example, imagine that I have a User class that depends on the Database class. The database class would return some information to the User class. However, if I am doing unit testing, I would like to test the User class on its on, with my own set of inputs. With dependency injection, I can easily inject my own mock objects (inputs) into the user class without having to set up a database with the test data and depend on the database to access and return that data to us.
Having said that, dependency injection is not a must or required for all projects. For example, a complex dependency injection framework may affect the performance or introduce unneeded complexity into your application.
You are injecting the whole registry. I suggest you should simply inject your dependency directly:
class Foo {
/**
* #Inject
* #var MyLogClass
*/
private $log;
}
That way your code is simpler to read and write, and you don't have to care about your registry.
This is possible for example with PHP-DI which works with annotations like the DI container you are using.