OOP Dependencies: Dependency Injection vs. Registry - php

I know some OOP and have read this and that, but am not a hardcore OOP guy and have no formal training and can't rattle off why something should use dependency injection or not, and may not be able to identify all dependencies in a design, hence my question.
Answering a question here on SO (Using a object in methods of other objects) I started to doubt myself. As far as dependencies, is one of these better or worse or both acceptable? Any design limitations?
I have read and understand both but haven't ever come across a comparison. Why would one be better used in a design, etc.
Dependency Injection:
class myClass {
private $db;
public function __construct($db) {
$this->db = $db;
}
}
Registry (maybe also something else):
class myClass {
private $db;
public function __construct() {
$this->db = Registry::get('db');
}
}

It has a lot to do with testability.
In your example, the first (Dependency Injection) is better. The reason it's better is because it accepts db as an argument, which means this is testable, you can use a mock db for testing and test myClass does the right thing with it.
The second example (Registry) is not recommended as not only myClass depends on db, it now also depends on Registry, and the worst part it's that it knows how to get a db. It's too smart, it should be dumb like the first one, dumb things are more testable, smart things are not.

Both methods are possible implementations of dependency injection. Basically dependency injection means to define a way to configure (inject) the classes to be used at runtime in order to make to code more flexible compared to using using hard coded class names and constructors in the code. Dependency injection follows a principle called inversion of control.
This is especially interesting for testing code but can be used in a variety of other scenarios where you want to make an application flexible and maintainable.
While dependency injection mostly is referred to as DI container, it can generally be done using a couple of different methods - which may also coexist. Here comes an (incomplete) list:
using a dependency injection container
pass class dependency as constructor or method args
using a central registry (as long as it is configurable)
using setter methods to set dependencies
using configuration files
user input
...

A dependency injection is required because the object needs certain data to perform its functions correctly.
Dependency Injection can be performed in three different ways:
If Object A depends on object B, then you can create object A while creating object B
You can use some external class ( like Registry, configuration files etc ) to load the dependency objects, This will decouple the creation of your object from the dependency creation. This is called locator pattern where your object creation is dependent upon the locator to load the objects.
You can create the dependency elsewhere and provide it directly to the dependent object. This is called 'manual injection'
Whenever you do any of these, you are already doing dependency injection:
Constructor injection
public class ClassA
{
// declares the dependency in the constructor
public function ClassA( dependency1:String )
{}
}
// and the dependency is created while instantiating the object
var objA:ClassA = new ClassA("Hello World");
Public property injection
public class ClassA
{
// declares the dependency as a public property
public var helloStr:String;
}
var obj1:ClassA = new ClassA();
// dependency is fulfilled by setting a public property after instantiation:
obj1.helloStr = "The Zen Master";

Related

Php Dependency Injection and namespaces

What it is the best way to implement a dependency injection, this way:
new App\Controllers\HomeController();
Class HomeController
use App\Views\HomeView;
class HomeController {
private $view;
public function __construct() {
$this->view = new HomeView();
or this way:
new App\Controllers\HomeController(new App\Views\HomeView());
Dependency injections is usually (if not always) done via a IoC (Inversion of control) - container. The container, or rather it's dependency injection logic takes care of creating the objects and through some magic fetches all the parameters expected to be added and creates them, also from the containers dependency injection logic.
What you are doing is rather just creating new objects. You could do that either way you wish, but personally I would probably pass the view through the constructor.
If you wish to read more about dependency injection and containers, id refer to the wiki entry about it.
You can also take a look at one of my naive implementations of a dependency container using php reflections here if you wish!
Samples you've provided reflect totally different approaches (I've left class naming same as you have):
// App/Controllers/HomeController.php
use App\Views\HomeView;
class HomeController {
private $view;
public function __construct() {
$this->view = new HomeView();
}
}
This is not dependency injection, you create the stuff your class depends on inside the class.
Compare to:
// App/Controllers/HomeController.php
use App\Views\HomeView;
class HomeController {
private $view;
public function __construct(HomeView $view) {
$this->view = $view;
}
}
This is actually dependecy injection: whatever your class needs is created outside of the class and passed to it via constructor (in this particular case).
Some tool (dependency injection container) may or may not be used to manage the dependencies depending on your case.
To get some more details please see the article https://martinfowler.com/articles/injection.html by Martin Fowler and search here on SO - the topic is extensively covered (What is dependency injection?, What is Dependency Injection?, When to use Dependency Injection).

Is it dependency injection and is it a bad practice?

I have a small framework and I coded it like this. I'm not sure if it is called dependency injection or not. I don't know if it is like a design pattern or not. I also don't know and wonder if passing $this as param is a bad practice.
Have a look at this; (Not a working example, just wrote those codes into browser for explanation.)
/* This is engine model */
require_once('Database.class.php');
require_once('Image.class.php');
require_once('Misc.class.php');
require_once('BBCode.class.php');
class FrameWork_Engine_Model
{
public $database, $config, $misc, $bbcode, $controller, $image;
function __construct($config)
{
$this->database = new Database($configParams);
$this->image = new Image($this);
$this->misc = new Misc($this);
$this->bbcode = new BBCode($this);
$this->controller = new Controller($this); //here I call Register controller depending on routing, in this case, register controller.
}
...
}
/* This is register controller */
class Register extends Base_Controller
{
/*I can access anything over Engine Model in my controllers */
$this->engine->database->query(); //I access database model
$this->engine->bbcode->tag('you'); //I access bbcode model
$this->engine->image->sanitizeUploadedFile(); //I access image model
//etc. I can access others models like this.
}
Basically, my controllers can access any models via engine model. I believe dependency injection is all about injecting dependencies into controllers? Like, my register controller needs a database model, routing model, and templating model to work. Here it has everything it depends on. Am I mistaken?
With those said, my questions are:
Is it a valid dependency injection example? If not, what it is? Does it have a name in design patterns?
If it is nothing related to dependency injection, what changes needs to be done to be DI?
Is passing $this parameter on newly created classes is a bad practise? If so, why?
Ps. I know asking 3 questions in a topic isn't something stackoverflow likes, but I don't want to copy paste entire text to ask them.
You are almost there.
Question 1
No, I don't see it as a valid dependency injection example. It resembles a bit a service locator (because you're injecting the entire container into your services and use it to "locate" dependent services).
Question 2
You're making a small confusion between dependency injection and a dependency injection container.
First of, dependency injection means pushing dependencies into an object at runtime instead of creating/pulling them.
To exemplify this:
//hardcoded dependecies
class BadService
{
public function __construct()
{
$this->dep1 = new ConcreteObject1();
$this->dep2 = new ConcreteObject2();
}
}
So in the example above, the BadService makes it imposible to wire other dependencies at runtime because they are already hard pulled into the constructor itself.
//service locator pattern
class AlmostGoodService
{
public function __construct(Container $container)
{
$this->dep1 = $container->getADep1();
$this->dep2 = $container->getADep2();
}
}
In the AlmostGoodService example, we've removed the hard dependencies from the previous example but we are still depending on a specific implementation of our container (meaning that our service is not reusable without providing the implementation for that container). This is the example that matches what you're doing.
//dependecy injection
class GoodService
{
public function __construct($dep1, OptionalInterface $dep2)
{
$this->dep1 = $dep1;
$this->dep2 = $dep2;
}
}
The GoodService service is not concerned with the creation of it's concrete dependencies and can easily be "wired" at runtime with any dependencies that implement the "protocol" of the $dep1 or the OptionalInterface for the $dep2 (therefore the name of Inversion of Control - the underlying concept behind Dependency Injection).
The component that does this wiring is called a dependency injection container.
Now, a dependency injection container, in it's simplest form, is nothing more than an object capable of wiring up your objects at runtime based on some form of configuration.
I said that you are almost there but there are some problems with your implementation:
the wiring should be lazy (you do not want to make all that work in your constructor, as your application would slow down considerably as it grows)
you should not pass the entire container ($this) as a dependency because then you fallback to a weaker inversion of control, namely a service locator. You should instead pass the concrete dependencies to your service constructors
Question 3
There are some cases when you'll find yourself wanting to pass the entire $container as a dependency to a service (namely controllers or lazy service factories), but generally it will be better to stay away from this practice as it will make your services more reusable and easier to test. When you're feeling that your service has too many dependencies, then that it's a good sign that you're service does too much and it's a good time to split it.
Prototype Container Implementation
So, based on my answers above, here is a revised (far from perfect) implementation:
/* This is the revised engine model */
class FrameWork_Engine_Model
{
function __construct($config)
{
$this->config = $cofig;
}
public function database()
{
require_once('Database.class.php');
return new Database($this->config['configParams']);
}
public function bbcode()
{
require_once('BBCode.class.php');
return new BBCode($this->database());
}
public function image()
{
require_once('Image.class.php');
$this->image = new Image($this->config['extensionName']);
}
....
public function register_controller($shared = true)
{
if ($shared && $this->register_controller) {
return $this->register_controller;
}
return $this->register_controller = new Register_Controller($this->database(), $thus->image(), $this->bbcode());
}
}
Now, to use your services:
$container = new FrameWork_Engine_Model();
$container->register_controller()->doSomeAction()
What could be improved? Your container should:
provide a way to share services - that is, to initialise them only once
be lockable - provide a way to lock it after configuration
be able to "merge" with other containers - that way your application will be really modular
allow optional dependencies
allow scopes
support tagging services
Ready to use DI Container Implementations
All of these are accompanied with clear documentation about Dependency Injection
Pimple - PHP 5.3 lightweight DI container
Symfony2 DI Container - PHP 5.3 feature full DI container
Juice DI - Small PHP 5.2 DI container
Your FrameWork_Engine_Model is a registry (Registry Pattern). Injecting the registry as dependency into all objects is kind of a misunderstood dependency injection. Technically it is DI, but you create a dependency from everything to everything and also take away the flexibility that DI should offer.
If your FrameWork_Engine_Model was meant to instantiate services and manage their dependencies, you could change it to an Inversion of Control Container (typical pattern related to DI)
No, not in general.
I won't argue your choice of class names and the responsibilities of your services and controllers, as I don't think it is within scope of this question. Just a remark: it looks like your controllers do too much. If you are interested in clean code, you might want to have a look at the Single Responsibility Principle and keep your controllers "thin", moving business logic and database queries to a service layer and output mechanisms like bbcode to views.
So, back to your example and how to change it to a sensible usage of Dependency Injection. A primitive IoC container could look like that:
public function createRegisterController()
{
$controller = new RegisterController();
$controller->setImage($this->getImageService());
// ...
return $controller;
}
public function getImageService()
{
if ($this->imageService === null) {
$this->imageService = new Image();
// inject dependencies of Image here
}
return $this->imageService;
}
The important point here is: Only inject the dependencies that are needed. And don't create a bunch of global variables disguised as DI.

unit testing with DI

I have a question concerning dependency injection. I have been keeping it simple so far, my methodology is basically to factor out object creation within objects and passing it instead in the constructer. I have come to a point where I am attacking larger classes that require multiple oblects. Some even have objects that contain other objects, with merry little singletons here and there. It gets ugly fast when testing these classes, as they are far from 'isolated' they are still hard-coded to their dependencies.
So. Injecting an object or 2 for a trivial class is straightforward,
I have looked into dependency containers, saw many implementations and am now wondering what is the advantage of using container vs. a registry for example. Couldn't one just as easily use a registry to hold anonymous functions that create the needed dependencies when called upon?
The 2 containers I peeked into, Php Dependency and Pimple differ greatly in the implementation.
I am wondering on the advantages of user a container vs. passing straight objects. I fail to understand how php-dependency's implementation would be tested, ie how would one implement the mock database object in phpunit without the actual class being injected when tested? Is there advantage to having dependency mapped out and used in doctags like this?
Class Book {
private $_database;
/**
* #PdInject database
*/
public function setDatabase($database) {
$this->_database = $database;
}
}
Pimple, on the other hand takes a totally different approach. No docblock tags, no mapping in seperate file, it seems like some kind of souped up registry ....
Objects are defined by anonymous functions that return an instance of the object:
// define some parameters
$container['cookie_name'] = 'SESSION_ID';
$container['session_storage_class'] = 'SessionStorage';
... that can behave as a factory at same time:
$container['session'] = function ($c) {
return new Session($c['session_storage']);
};
Declaring shared ressources always serves the same instance (singleton!?):
$c['session'] = $c->share(function ($c) {
return new Session($c['session_storage']);
});
This is were I got the idea of using a simple registry that holds either objects or anonymous functions. BUt am I missing something in this approach? Pimple, I can see to how to test, but Php-Dependency is unclear to me from a testing point of view.
Normally in our apps, we do constructor injection and define an interface for all components in our system:
class Book
{
/**
* #var Db_AdapterInterface
*/
private $_database;
public function __construct(Db_AdapterInterface $database)
{
$this->_database = $database;
}
}
We have then of course a standard Db_Adapter and then another Db_TestAdapter. In Db_TestAdapter we can define results of SQL queries in our tests.
For our normal app, we have something like this for our container:
$container->add('Db_AdapterInterface', new Db_Adapter());
And then in our tests, we have this line instead:
$container->add('Db_AdapterInterface', new Db_TestAdapter());
To get an instance of a Book, we simply ask the container for it:
$book = $container->construct('Book');
And the container injects all the needed dependencies into the object.
If you keep all your objects loosely coupled, ie object A only needs an interface B then you can always provide object A with a test implementation. At that point what container you use doesn't matter.
We have a very simple IoC container which can do basic constructor injection. Our tests inherit from a base class which fills the container with standard test objects. That way we don't have a lot of code just to construct an object we want to test.
Update:
I added an example of wiring things up in the container.

Having issues understanding Dependency Injection

I'm building out a small project to try to teach myself as much of the fundamentals as possible, which for me means not using a prefabricated framework (As Jeff once put it, "Don't reinvent the wheel, unless you plan on learning more about wheels" [emphasis mine]) and following the principles of Test Driven Development.
In my quest, I recently ran into the concept of Dependency Injection, which appears essential to TDD. My problem is that I can't quite wrap my head around it. My understanding so far is that it more or less amounts to "have the caller pass the class/method any other classes it may need, rather than letting them create them themselves."
I have two example issues that I'm trying to resolve with DI. Am I on the right track with these refactorings?
Database Connection
I'm planning to just use a singleton to handle the database, as I'm currently not expecting to use multiple databases. Initially, my models were going to look something like this:
class Post {
private $id;
private $body;
public static function getPostById($id) {
$db = Database::getDB();
$db->query("SELECT...");
//etc.
return new Post($id, $body);
}
public function edit($newBody) {
$db = Database::getDB();
$db->query("UPDATE...");
//etc.
}
}
With DI, I think it would look more like this:
class Post {
private $db; // new member
private $id;
private $body;
public static function getPostById($id, $db) { // new parameter
$db->query("SELECT..."); // uses parameter
//etc.
return new Post($db, $id, $body);
}
public function edit($id, $newBody) {
$this->db->query("UPDATE..."); // uses member
//etc.
}
}
I can still use the singleton, with credentials specified in the application setup, but I just have to pass it from the controller (controllers being un-unit-testable anyway):
Post::getPostById(123, Database::getDB);
Models calling models
Take, for example, a post which has a view count. Since the logic to determine if a view is new isn't specific to the Post object, it was just going to be a static method on its own object. The Post object would then call it:
class Post {
//...
public function addView() {
if (PageView::registerView("post", $this->id) {
$db = Database::getDB();
$db->query("UPDATE..");
$this->viewCount++;
}
}
With DI, I think it looks more like this:
class Post {
private $db;
//...
public function addView($viewRegistry) {
if ($viewRegistry->registerView("post", $this->id, $this->db) {
$this->db->query("UPDATE..");
$this->viewCount++;
}
}
This changes the call from the controller to this:
$post->addView(new PageView());
Which means instantiating a new instance of a class that only has static methods, which smells bad to me (and I think is impossible in some languages, but doable here because PHP doesn't allow classes themselves to be static).
In this case we're only going one level deep, so having the controller instantiate everything seems workable (although the PageView class is getting its DB connection indirectly by way of the Post's member variable), but it seems like it could get unwieldy if you had to call a method that needed a class that needed the class that needed a class. I suppose that could just mean that's a code smell too though.
Am I on the right track with this, or have I completely misunderstood DI? Any criticisms and suggestions are greatly appreciated.
Yes. It looks like you have the right idea. You'll see that as you implement DI all your dependencies will float to the "top". Having everything at the top will make it easy to mock the necessary objects for testing.
Having a class that needs a class that needs a class is not a bad thing. What your describing there is your object graph. This is normal for DI. Lets take a House object as an example. It has a dependency on a Kitchen; the Kitchen has a dependency on a Sink; the Sink has a dependency on a Faucet and so on. The House's instantiation would look something like new House(new Kitchen(new Sink(new Faucet()))). This helps to enforce the Single Responsibility Principle. (As an aside you should do this instantiation work in something like a factory or builder to further enforce the Single Responsibility Principle.)
Misko Hevery has written extensively about DI. His blog is a great resource. He's also pointed out some of the common flaws (constructor does real work, digging into collaborators, brittle global state and singletons, and class does too much) with warning signs to spot them and ways to fix them. It's worth checking out sometime.
Dependency injection is about injecting. You need some solution to inject the external object.
The traditional approaches are:
constructor injection __construnctor($dependecy) {$this->_object = $dependency}
setter injection setObject($dependency) {$this->_object = $dependency}
gettter injection getObject() {return $this->_dependency} and oveloading this method eg. from stub or mock in the tests.
You may also mix all the above, depends what you need.
Avoid static calls. My personal rule is use static only when you call some functions, e.g. My::strpos() or when dealing with singletons or registry (which should be limited to minimum, because global state is evil).
You will rarely need static methods when your app has a good dependency container.
Take a look at the other dependency injection + [php] topics on SO.
Edit after comment:
The container
Different frameworks handle the container in different way. Generally this is an object, which holds the instances of objects you need, so you don't have to instantiate new object each time. You may register any object with such a container, and then access it anytime you need.
The container may instantiate all the resources you need at boot time, or lazy load the resource when accessed (better solution).
As an example, consider:
Zend Application Resource Plugins
Symfony Dependency Injection Container
Another great reference:
http://martinfowler.com/articles/injection.html
It's certainly going into the right direction but you should not stop there.
The point of DI is to remove strong couplings between classes to allow for easier substitution of single components. This will allow for better testability because you can substitute dependencies more easily with Mocks and Stubs. And once your code is tested, it is much easiert to change and maintain.
Consequently, you should also remove those other aspects in your code that create strong coupling smells as well, e.g. remove the static methods and the singleton and any other globals.
For some more information on that, please see
How is testing the registry pattern or singleton hard in PHP?
http://gooh.posterous.com/singletons-in-php
http://kore-nordmann.de/blog/0103_static_considered_harmful.html
http://fabien.potencier.org/article/11/what-is-dependency-injection
EDIT: with a couple of others answers suggesting to use a DI container, I feel it's necessary to stress that you do not need a DI container to do DI. The second blog post in the last link given above discusses this.
To answer your questions: yes, you are on the right track. To give you more details: this is one of the best posts I found related to DI:
http://www.potstuck.com/2009/01/08/php-dependency-injection
You will understand what a container is:
$book = Container::makeBook();
Regarding the second example: in your method addView I would try to avoid passing the object $viewRegistry, I would check the condition outside in the controller.

How can I use "Dependency Injection" in simple php functions, and should I bother?

I hear people talking about dependency injection and the benefit of it all the time, but I don't really understand it.
I'm wondering if it's a solution to the "I pass database connections as arguments all the time" problem.
I tried reading wikipedia's entry on it, but the example is written in Java so I don't solidly understand the difference it is trying to make clear. ( http://en.wikipedia.org/wiki/Dependency_injection ).
I read this dependency-injection-in-php article ( http://www.potstuck.com/2009/01/08/php-dependency-injection/ ), and it seems like the objective is to not pass dependencies to an object directly, but to cordon off the creation of an object along with the creation of it's dependencies. I'm not sure how to apply that in a using php functions context, though.
Additionally, is the following Dependency Injection, and should I bother trying to do dependency injection in a functional context?
Version 1: (the kind of code that I create, but don't like, every day)
function get_data_from_database($database_connection){
$data = $database_connection->query('blah');
return $data;
}
Version 2: (don't have to pass a database connection, but perhaps not dependency injection?)
function get_database_connection(){
static $db_connection;
if($db_connection){
return $db_connection;
} else {
// create db_connection
...
}
}
function get_data_from_database(){
$conn = get_database_connection();
$data = $conn->query('blah');
return $data;
}
$data = get_data_from_database();
Version 3: (the creation of the "object"/data is separate, and the database code is still, so perhaps this would count as dependency injection?)
function factory_of_data_set(){
static $db_connection;
$data_set = null;
$db_connection = get_database_connection();
$data_set = $db_connection->query('blah');
return $data_set;
}
$data = factory_of_data_set();
Anyone have a good resource or just insight that makes the method and benefit -crystal- clear?
Dependency injection is a big word for "I have some more parameters in my constructor".
It's what you did before the awfull Singleton wave when you did not like globals :
<?php
class User {
private $_db;
function __construct($db) {
$this->_db = $db;
}
}
$db = new Db();
$user = new User($db);
Now, the trick is to use a single class to manage your dependencies, something like that :
class DependencyContainer
{
private _instances = array();
private _params = array();
public function __construct($params)
{
$this->_params = $params;
}
public function getDb()
{
if (empty($this->_instances['db'])
|| !is_a($this->_instances['db'], 'PDO')
) {
$this->_instances['db'] = new PDO(
$this->_params['dsn'],
$this->_params['dbUser'],
$this->_params['dbPwd']
);
}
return $this->_instances['db'];
}
}
class User
{
private $_db;
public function __construct(DependencyContainer $di)
{
$this->_db = $di->getDb();
}
}
$dependencies = new DependencyContainer($someParams);
$user = new User($dependencies);
You must think you just another class and more complexity. But, your user class may need something to log messages like lot of other classes. Just add a getMessageHandler function to your dependency container, and some $this->_messages = $di->getMessageHandler() to your user class. Nothing to change in the rest of your code.
You'll get lot of infos on symfony's doc
Your first example IS dependancy injection, you are injecting the dependency on the database object into the function.
Sarah has said this isn't, but imo it is, I believe she is thinking of dependency injection containers which are the next level up:
http://components.symfony-project.org/dependency-injection/trunk/book/02-Dependency-Injection-Containers
None of your examples look like dependency injection, version one is the closest though. Dependency injection is a technique used in object oriented programming, where the constructor of an object has arguments for the service objects it needs, and those service objects are passed in by the creator of the instance (which could be a factory, a test, or a dependency injection framework).
To get around your 'always passing the connection object' problem you may want to consider the template pattern. The template pattern is basically an abstract base class with the common part of a repeated code block, and abstract methods to allow for the variation between the instances of those repeated code blocks. Basically the base is a template of a block of code, and the abstract methods are the blanks to be filled in. I personally use the template method pattern to do my database resource control in Java.
I have done much searching on this topic myself (PHP Dependency Injection) and haven't found much to my liking. A lot has been written on the subject for other languages (Google Guice - http://code.google.com/p/google-guice/ ; Java Spring), but I couldn't find much available for PHP. Regardless of the language, however, the challenges are similar.
The three versions you list in your question are the typical approach. Version 3 is the closest to the direction in which I have seen the industry going. By shifting the responsibility of creating your dependent objects outside of your class, you are free to manipulate them as you please in your test code. However, the problem that I encountered with that approach is that you end up with long chains of dependent objects in your constructor that can potentially not even be used by the receiving object, but get passed through to an secondary dependent object. It gets messy and you lose knowledge of what is coming from where.
The Dependency Container example by #Arkh and #mmmshuddup is a great start, but I nonetheless found limitations with that approach as well. The final solution upon which I arrived was a custom built solution modeled somewhat after the Cake Pattern popular in Scala. It allows you to pass a single dependency into each of your constructors AND it lets you define the default construction of the dependent objects per class. This frees you from long dependency chains as well as losing control of the default implementations of your dependencies.
I called the system Diesel and I've been really happy with it. I published the code on github for anyone interested. You can get to it from the blog I wrote on the subject, which describes the basic usage as well as goes into more detail on your question. http://developers.blog.box.com/2012/02/15/introducting-diesel-php-dependency-injection/
Dependency Injection is the idea of removing the dependency between 2 components in order to focus on why they are dependent.
Imagine you have a component A that needs to use the services of another component B.
If you hardcode the existence of B inside A, then you will be stuck when you will want A to use the sames services, but implemented by another component.
So usually, you define a service interface that B and C will implement, and you make sure that when you use A, you feed it with objects compatible with the needed interface.
In your case, you might consider that your interface is a service on which you can make a query.
Your first case is the one that is the closer to the idea of Dependency Injection.

Categories