dependency-injection

Wow - dependency injection in PHP is a really bad idea

I’m not a huge fan of dependency injection. Anytime you move logic out of code and into some XML file you’re making your application harder to understand. 

The argument for dependency injection is that it makes your application more flexible by creating a loose coupling between components. So rather than having a hard-coded line of code to instantiate a concrete instance of some logger class, instead you move the type choice out into some configuration file.

Dependency injection was popularized by the Spring framework in Java. Now I can almost, sort of, see the benefit of DI when using Java, where the compile-jar-startup cycle can be quite long. (Although I think most cases are probably better handled by a basic factory pattern.) When you’re using a static-typed language like Java, then DI can introduce some late binding where types don’t have to be resolved until runtime.

But recently I’ve gotten the peculiar pleasure of getting to work on a PHP application using the Symfony 2 framework. Symfony includes a DI system taking inspiration from Spring. They even have a really nice web page describing the system, which includes this great feature: “comes bundled with a Graphviz dumper, allowing you to visualize the graph of your objects and ease the debugging of your container”. 

The only problem is that dependency injection is a terrible idea in PHP. After all, PHP is a loosely typed, dynamic language. If you want to use a different class for your logger, well then you just assign your “logger” variable to some other object. Objects are duck-typed in PHP, you can call “logMessage” on any old object you like. There’s no compile-link-debug cycle to avoid by moving type resolution into some XML file!!

You want to choose a different logger at runtime? Just set some config option (say in php.ini or your own config system or in an env variable) and choose your logger class at runtime based on the config value. You can even put the logger class name in your config, and use: “$logger = new $loggerClassName;”. Please, please, do not start littering your code with XML files, and forcing yourself to “visualize the graph of your objects to ease debugging of your container”!! 

Dependency injection is a crummy solution to a problem specific to the limitations of complex, statically-typed systems. It really has no benefit in a dynamic language like PHP.

What is so bad about static classes?

Someone asked me “what is so bad about static classes” during the “O” in my SOLID presentation http://solid.architecture.michaelkappel.com/Principles/OCP/. My response was that can not inherited from so that makes their members closed to extension. (Actually I stumbled a little said something else but that is what I meant.)

Static classes in general preclude the use of dependency injection. Dependency injection is crucial to being able use Mock objects necessary to isolate functionality in order to do proper unit testing. Static classes calling static classes make code to tightly coupled. Tightly coupled code is more likely to require changes because it has direct dependencies. Those dependencies increase the likelihood that when a static method is modified it may cause unexpected behavior in another static.  It is always true when you are not closed for modification you are likely to introduce new bugs but it seems to be amplified when static methods call other static methods because it can cascade change. 

Using static classes in general increases the probability of the introduction of new bugs and makes fixing them harder because you can not isolate functionality.

Static and Extension Methods do serve to decrease the complexity of code so I guess it is all about using them at the correct time for the right reason but in general is incompatible with the SOLID software approach.

nO, cOME ON, i BET I COULD LIFT YOU, i’M ACTUALLY STRONGER THAN I LOOK,

yOU’RE NOT EVEN TALLER THAN ME, eXCEPT BY A LITTLE BIT, i MEAN, aND YOU’RE REALLY SKINNY,

hERE, uH, cHECK THIS OUT!

(sketched this last night and couldn’t let the freaking thing go so I had to do lineart and shading ahahahah i have no impulse control whatsoever)

(What percentage of the drawings on this blog would be wearing shirts if I hadn’t loved how the base sketches turned out, I wonder?  =u= Shirtless smiling boys, the blog.)

(Bonus)

(*EXCITED FLAILING AND CRIES OF ‘—MOTHERFUCKER!’*)

Constructor Based DI Demo

Here is a simple demonstration of constructor injection using an IOC container. This demo includes a Unity and Autofac implementation.

Constructor injection means the dependencies (parameters on a constructor) are resolved by looking inside a IOC container (graph of dependencies). This allows us to write classes that simply express the things they are dependent on via the constructor. To increase loose coupling, interface types are commonly used as parameters. 

Consider the following context: a banking service that uses some other services, specifically a account service and a user service. The account and user services use common services for things like logging, caching, auditing, etc. The interfaces for these services might looks something like this:

Now we provide an implementation for each of these services. On the constructor we’ll add interface parameters to other services the class is dependent on. Consider the following mocked account service for example:

We are saying this service requires a IAuditService, a ICacheService, and a ILoggingService. We simply set the instances provided to us as private members of the class and we can then use them throughout the implementation of the class, like so:

We can follow the patterns above for all our services, adding interface parameters to the constructor and setting local member fields. When we are ready to run the program we need to first build up the dependency graph (IOC Container). We have defined an interface for resolving instances out of a container, it looks like this:

As you can see, it only does one thing: resolves types. So it’s up to the class that implements this interface to build up the container in its constructor. Here is a Unity based sample:

And here is a Autofac based sample:

The above graph of dependencies can be visualized like so:

Now we can run the following program to see both Unity and Autofac based approaches to dependency injection via our IIOCContainer interface:

Running the above program shows us both IOC containers are used to do the same thing, provide dependencies to constructors:

As you can see the exact same thing happened in each test, but completely different containers where used in the two tests. Hopefully this demo will give you a good starting point for your loose coupling designs.

The source code for this demo can be found here:

http://iocdemo.codeplex.com/

Dependency Injection  vs Factory

Dependency Injection (DI) has been a hot topic since at least 2003 and onwards. Lots of dependency injection frameworks have appeared (including my own Butterfly DI Container), and lots of forums and blogs has discussed the technique. Yet I still experience big enterprise software development departments, who have not yet embraced the idea. Instead I see them using the Factory design patterns extensively in situations when dependency injection would have been a far more flexible solution to the same problem.

Of course this is sometimes the case when old code is being maintained, which was written, or at least started, before dependency injection became mainstream. The factory pattern is then adhere to for consistency with the old code. But sometimes I also see the factory pattern used in completely new code.

This text will show how dependency injection is the next evolutionary step after the Factory design patterns, in the persuit of loosely coupled components.

Read more …

Your application almost certainly uses some kind of data layer (whether it is Ember-Data, EmuEmber-ModelEmber-Resource, or a solution you rolled yourself), but what do you do when you need to load some data asynchronously, when it isn’t quite important enough to be a model?

For example, when a user edits her profile, you may allow her to choose from a list of countries. This can be a rather long list that you’d rather not hard-code into your application. But it also may feel like overkill to create full-fledged models for this seldom-used, read-only list of data.

// services/countries.js
App.CountriesService = Ember.Object.extend({
  promise: function() {
    return Ember.$.getJSON('/api/countries');
  }.property(),

  all: function() {
    var promise = this.get('promise');
    return Ember.ArrayController.extend(Ember.PromiseProxyMixin).create({
      promise: promise
    });
  }.property()
});


var countries = App.CountriesService.create();

countries.get('all'); // Makes a request and returns a promise proxy array
countries.get('all'); // Returns the same promise proxy without a second request


Here’s a JSBin

A Paperclip Refactoring Tale: Part One: Dependency Injection

The Beginnings

Good refactoring has a goal. The goal of this refactoring is to make it easier for people to hook into Paperclip.

To start I surveyed existing gems, plugins, and apps that hook into Paperclip. I took a quick glance through Github and found that delayed_paperclip, mongoid-paperclip, papermill, paperclip-extended, and paperclip-facecrop all served as good sample gems that change Paperclip in unique ways. My end desire was to remove the need for monkey patching, and if I could go one further to remove the need for subclassing that’d be even better.

Papermill is a sample Rails app that uses Paperclip, extending it with watermarking, copyrighting, and a custom geometry string. It does this by extending the existing thumbnail Paperclip processor, overriding two methods: the constructor and transformation_command. The new constructor does a ton of parsing: the geometry string is parsed for options indicating a desire to add a copyright or watermark, the copyright or watermark string is extracted from the options, and cropping offsets are parsed out too. It uses all of this to manipulate the transformation_command, like this: it invokes the super's transformation_command, which produces a string. It then subs the string, sticking various bits set from the constructor into the middle of the command. The watermarking aspect is particularly tricky, since it must change the convert command to a convert ... | composite command, using string manipulation.

This will not do.

The Abstractions

The first change I made was to parameterize the geometry parsing (3f7aee3 and eebc7d9). Now if you want a Thumbnail-based processor but with a custom geometry parser you can do that right from has_attached_file:

has_attached_file :avatar,
  :styles => {:medium => {
    :geometry => '80x60#10x5:2x1',
    :string_geometry_parser => CroppingGeometryCommandParser.new
  }}

This change looks a little like this. Before:

module Paperclip
  class Thumbnail < Processor
    def initialize(file, options = {}, attachment = nil)
      super

      geometry             = options[:geometry] # this is not an option
      @file                = file
      @target_geometry     = Geometry.parse(geometry)
      @current_geometry    = Geometry.from_file(@file)
    end 
  end
end

After:

module Paperclip
  class Thumbnail < Processor
    def initialize(file, options = {}, attachment = nil)
      super

      geometry             = options[:geometry] # this is not an option
      @file                = file
      @target_geometry     = (options[:string_geometry_parser] || Geometry).parse(geometry)
      @current_geometry    = (options[:file_geometry_parser] || Geometry).from_file(@file)
    end 
  end
end

The change? Instead of hardcoding the Geometry class it instead takes it as an argument. The geometry parsing can now be replaced by any arbitrary object. In the tests, for example, instead of creating files that parse to the proper size or instead of stubbing, you can just pass an object that has a #from_file method and produces the correct object. The Geometry class is still the default for legacy reasons.

I split these into the string_geometry_parser and file_geometry_parser because they do different tasks: one takes a file and produces an object that knows how to produce the desired scaling and cropping arguments (lets call this the transformation), and another produces an object that is passed to the transformation.

With that small but powerful change out of the way I took a look at paperclip-extended. This is an old gem; many of these extensions have been rolled into Paperclip by now. The only thing that was impossible without monkey patching was the extended interpolations. For example, normally you can have a file path like /system/images/:rails_env/:id/i:basename.:extension and the :rails_env, :id, :basename, and :extension will be replaced with proper values—but it was impossible to add new interpolation values, such as :normalized_basename (removing non-alphanumerics).

The fix for this (7478455) is similar to that for geometry parsing: pass a custom interpolator to the Attachment through has_attached_file:

has_attached_file :avatar,
  :interpolator => InterpolatorWithNormalization.new

This change takes place in the Attachment class. Before:

module Paperclip
  class Attachment
    def interpolate(pattern, style_name = default_style)
      Paperclip::Interpolations.interpolate(pattern, self, style_name)
    end
  end
end

After:

module Paperclip
  class Attachment
    def initialize(name, instance, options = {})
      @interpolator = (options[:interpolator] || Paperclip::Interpolations)
    end

    def interpolate(pattern, style_name = default_style)
      @interpolator.interpolate(pattern, self, style_name)
    end
  end
end

Again, a straight-forward change that makes this class easier to test and also adds more extensibility.

The Reasonings

This is dependency injection. It is a very boring and simple principle that goes like this: abstract out class names where possible. This gains you both ease of testing and straight-forward hooks for extensibility.

You just saw two examples of it from a real project, so I’ll follow it up with an example from nothing:

Before:

class Car
  def gas
    puts "Vroom putter putter putter"
  end

  def brake
    puts "screeeetch!"
  end
end

After:

class Car
  attr_accessor :engine

  def initialize(engine)
    @engine = engine
  end

  def gas
    engine.go!
  end

  def brake
    engine.stop!
  end
end

This gains you testing ease:

describe Car do
  let(:engine) do
    Class.new do

      def go!
        @has_gone = true
      end

      def stop!
        @has_stopped = true
      end

      def has_gone?
        @has_gone
      end

      def has_stopped?
        @has_stopped
      end

    end.new
  end

  subject { Car.new(engine) }

  it "goes" do
    car.gas
    engine.should have_gone
  end

  it "stops" do
    car.brake
    engine.should have_stopped
  end
end

… and flexibility:

yuppie = Person.new(:car => Car.new(HybridEngine.new(:diesel => 40, :electricity => 60))
bro = Person.new(:car => Car.new(V12Engine.new(:mpg => 2))

Y’all

Now you get to use this. Things you can do:

  • Write a Gem that provides a custom Paperclip interpolator. Encrypt file names, handle uppercase/lowercase issues, offer the time of day, offer a random number, and so on—anything you need!
  • Write a gem that provides a custom Paperclip geometry sizer. It scales and crops images differently. For example, pick out people’s faces, crop from the center, measure hard-to-measure images, and so on.
  • While refactoring your code use a dependency injection principle somewhere. Instead of Net::HTTP use a passed-in object; same for any credit card processing, Tweeting, file-writing, logging, and so on.
Dependency Injection in ASP.NET vNext

Motivation

Microsoft changed the way how dependency injection (DI) is done in ASP.NET vNext. In previous versions of ASP.NET there were different entry points for user defined classes like the IControllerFactory for ASP.NET MVC applications or the IHttpControllerActivatorfor ASP.NET WebAPI applications. Starting with ASP.NET vNext DI becomes a first-class citizen in the framework through the…

View On WordPress

Dependency Injection in Akka with Scaldi

As a follow-up to the post about Scaldi Play integration I would like to introduce you an integration with the Akka in this post.

Akka integration is pretty recent addition to scaldi and interestingly enough has not much to add to the core library in order to smoothly integration with the Akka. In order to use it you need to add scaldi-akka to the SBT build, so let’s do this first:

libraryDependencies ++= Seq(
  "org.scaldi" %% "scaldi-akka" % "0.3.1"
)

Keep reading

Dependency Injection pattern. Using Google Guice

Google Guice is a library providing clear and simple (btw very powerful) implementation of Dependency Injection (DI) mechansm for Java application.

According to wiki, the Dependency Injection pattern involves at least three elements:

  • a dependent consumer,
  • a declaration of a component’s dependencies„ defined as interface contracts,
  • an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interfaces on request.

This means the typical situation for DI is having several interfaces and their implementations and a consumer class being constructed from them.

Example:

public interface IService1
{
    public void doRoutine1();
}


public interface IService2
{
    public void doRoutine2();
}


public class Service1Impl implements IService1
{
    public void doRoutine1()
    {
        System.out.println("Doing routine 1");
    }
}


public class Service2Impl implements IService2
{
    public void doRoutine2()
    {
        System.out.println("Doing routine 2");
    }
}


public class Service3
{
    private final IService1 service1;
    private final IService2 service2;

    @Inject
    public Service3(IService1 service1, IService2 service2)
    {
        super();
        this.service1 = service1;
        this.service2 = service2;
    }
    
    public void doRoutine()
    {
        service1.doRoutine1();
        service2.doRoutine2();
    }
}


public class GuiceModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        bind(IService1.class).to(Service1Impl.class);
        bind(IService2.class).to(Service2Impl.class);
    }
}


public class TestGuiceCheck
{
    public static void main(String[] args)
    {
        Injector injector = Guice.createInjector(new GuiceModule());
        Service3 srv3 = injector.getInstance(Service3.class);
        srv3.doRoutine();
    }
}

According to therminology, service 1 and service 2 are dependencies, service 3 is a dependent consumer and GuiceModule is an injector.

What we’ve gained here?

  • Very clean implementation of constructor Injection. As you can see from the example you just add @Injection annotation constructor
  • Don’t need to manually manage dependencies (becomes a problem when the number of dependencies overcomes 50-100)
  • We have interface-implementation binginds. Furthermore, we can use different bindings and contexts (see Guice project page for information)

So what are the benefits of using Guice and DI pattern?

  1. Easeness in unit testing
  2. Full dependency control
  3. One point of getting all the instances needed
  4. No problem with several instances of the same class (singletons aren’t good)
  5. Helps to code to interfaces, not to implementations
Watch on jvmblog.com

The Reader Monad for Dependency Injection - Jason Arhart

PHP Dependency Injection with Service Locator

In PHP, Dependency Injection lets us inject instances of objects into other objects so we don’t have to rely on using Singletons and even worse, Globals.  In this tutorial, we are bending the rules of dependency injection slightly by assigning dependencies to static keywords rather than setting via a method.

To explain, first of all let me show you how you would normally access an instance of a class from within another class method using a Global.

class globalClass{
  private $myGlobalClassProperty = '3';
  
  public function getMethod() {
    return $this->myGlobalClassProperty;
  }
}

$myGlobalClass = new globalClass();

class myClass() {

  private function myClassMethod() {
    global $myGlobalClass;
    return $myGlobalClass->getMethod();
  }
}

The above usage of globals isn’t ideal, so how do we access an object instance from within another object?  This is where dependency injection comes into play.  First we need to create a controller, you can also call this a container if you prefer.  Basically the only roll our controller will do is house all our potential global instances in one place for us to access to our hearts content.  We have kept this class static so never have to create or depend on any instances of it - this keeps our code clean.

// Here we set our instances into the container 
// class which houses all our potential globals class InC_Controller {
// lets define the keywords for the
// instances we want to hold public static $database; public static $Session; public static $User; // returns a dependency over static method public static function getDependency($dependency) { return self::$$dependency; } }

Next for the purposes of this tutorial, we are going to create a User class, this will house user info.  We have set a property called $this->info to hold “User Profile for John”.  We will then assign an instance of User directly to our controller object above.


// Our User Class class User { private $info = 'User Profile for John'; function getUserInfo() { return $this->info; } function setUserInfo($i) { $this->info = $i; } }

Here we assign our User instance to the controller.  Next we are going to access the setUserInfo method of our User instance via a static method of our Controller object so we can change the User profile from John to Brian.  If we call on getUserInfo, we can print the output to screen, this should display “User Profile for Brian”. 


// Next we assign our User Instance to our controller InC_Controller::$User = new User();
// We can now access our User methods
// directly via our Controller service controller InC_Controller::getDependancy('User')->setUserInfo('User Profile for Brian'); echo InC_Controller::getDependancy('User')->getUserInfo();
 

In our final demonstration of dependency injection with Service Locator, we are going to access our controller from within another class using the service locator, replacing the need to use a global.  First we create a fictitious class called cool, and a method called getCoolUser.  Upon creating an instance of cool, and then calling upon the method getCoolUser, we can output “User Profile for Brain” to the screen, thus saving having to manage and declare globals for instances we may need to use here and there.  Uses for this include instances of database and session objects.

class cool {

    public function getCoolUser() {
// We can also access our User instance
// methods from within other classes,
// no need for Globals!
 return InC_Controller::getDependancy('User')->getUserInfo(); } } // Outputs User Profile for Brian $cool = new cool(); echo $cool->getCoolUser();
Dependency Injection with Static constructor?

No

The short answer to the question is no. It simply does not make sense. Since the static constructor gets called by CLR , the static constructor can’t have parameters. Therefore, the constructor injection will not be possible.

Why I wanted to do this?

I normally create a helper class for configuration data as a facade for convenient access to data such as xml stored in web.config. This approach gives me a couple of advantages.

  • First, I can immediately start working with dummy configuration which is hard coded in the helper class before I actually create a repository for real configuration data.
  • Second, the configuration data is not all over the place since the helper object is a single place to manage all configuration data. If I have to make some radical changes to the configuration repository such as switching from web.config to a database, all I can replace is the helper class.

The helper class has a static method that returns the image uri based on the image id. And the image service format is hard coded

public class ConfigurationHelper
{
    public static string GetImageUri(long imageId)
    {
         // TODO: Get the service address format from web.config
         return string.Format("http://imageservice/{0}.xml", imageId);
    }
}

Problems

I soon encountered an issue when I tried to create unit tests for the asp.net mvc project. the ConfigurationHelper contains only static methods. 

Image action in the home controller

public ActionResult Image(string id)
{
	long imageId;

	if (!long.TryParse(id, out imageId))
	{
		throw new System.ArgumentException();
	}

	// Construct image service url.
	ViewBag.ImageServiceUri = ConfigurationHelper.GetImageUri(imageId);
	return View();
}

Issues with Unit Tests

I had this issue before many times. Basically, I had to duplicate the configuration data in the unit tests project. It’s not hard to do, except it’s a pain. You have to make sure the configuration data is synced up with the test project. I am pretty sure there is a way to copy the configuration to the test project automatically but it’s still not a good idea that your unit tests are dependent on the configuration data. So I decided to mock the ConfigurationHelper class in the test project so it will never fail. Therefore, it will never break the unit tests.

So I refactored the code as below. And then I got stuck again here.

	
public class ConfigurationHelper
{
	private static IConfigurationRepository configRepository = null;
		
	/// 
	/// Get the image service address based on the configuration
	/// 
	/// an image id
	/// the uri for the specified image.
	public static string GetImageUri(long id)
	{
		return string.Format(configRepository.ImageServiceAddressFormat, id); 
	}
}
public interface IConfigurationRepository
{
	string ImageServiceAddressFormat {get;}
}

I want to find out a way to inject an implementation of IConfigurationRepository and below is a hack. I created a static method called “Inject”.

	
public class ConfigurationHelper
{
	private static IConfigurationRepository configRepository = null;

	/// 
	/// Injects configuration repository
	/// 
	/// configuration repository
	public static void Inject(IConfigurationRepository repository)
	{
		if (configRepository == null)
		{
			configRepository = repository;
		}
	}

	/// 
	/// Get the image service address based on the configuration
	/// 
	/// an image id
	/// the uri for the specified image.
	public static string GetImageUri(long id)
	{
		return string.Format(configRepository.ImageServiceAddressFormat, id); 
	}
}

Manually inject the dependency on Global.aspx.cs

IUnityContainer container = new UnityContainer()

container.LoadConfiguration("default");
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

// TODO: It's a manual injection because the static constructor does not take parameters
// Let me know if you know a better way to inject dependancy for static methods				
ConfigurationHelper.Inject(DependencyResolver.Current.GetService());

Back to Unit Test

Mock ConfigurationHelper using Moq framework

private void SetUpConfigurationHelper()
{
	var configStub = new Mock();
	configStub.Setup(x => x.ImageServiceAddressFormat)
					  .Returns(ImageServiceFormat);
	ConfigurationHelper.Inject(configStub.Object);
}
[TestCase("1")]
[TestCase("268435456")]
[TestCase("68719476736")]		
public void HomeController_Image_Test(string id)
{			
	var stub = new Mock();			

	using (var controller = new HomeController(stub.Object))
	{
		var result = controller.Image(id) as ViewResult;

		Assert.IsInstanceOf(result, "The result should be a ViewResult type instance");
		Assert.IsTrue(!string.IsNullOrEmpty(result.ViewBag.ImageServiceUri));

		Assert.AreEqual(string.Format(ImageServiceFormat, id), result.ViewBag.ImageServiceUri);
	}
}