Tiny IoC module for static mocking in PHP

v1.0.0 2014-04-12 08:01 UTC

README

Inversion Of Control

Build Status Total Downloads License

"Don't call me let me call you"

  • Have you ever heard about Inversion Of Control / Dependency Injection in PHP ?
  • Know some giants like Symfony Service Container or Laravel Facades ?
  • Wishing you could use Inversion Of Control (IoC) and Facade Design Pattern in your legacy source code ?

I think I can help you a little bit ! Let's start :)

Quick Start

This tiny packge will provide an easy and lightweight way to implement IoC

  • Include following lines in your composer.json
    "require": {
        "orakaro/ioc": "dev-master"
    }
  • Get classes autoloaded
composer dump-autoload
  • Done ! Now head over Usage section !

Usage

Let me assume that you have some class like

<?php
class Library{
  public function overview()
  {
    $book = Book::getTitle($ISBN);
    return $book;
  }
}

Note that overview method is using Bookclass's static method getTItle here.

Now let's create another file call IoCRegister.php

<?php
require_once __DIR__ . '/vendor/autoload.php';//Shoule be correct path to composer autoload!
use orakaro\IoC\core\IoC;

class IoCRegister{
  public static function registerAll()
  {
    /* IoC register for Book::getTitle */
    IoC::register('Book_getTitle', function($ISBN){
        return Book::getTitle($ISBN);
    });
  }
}

class IoCBook{
  public static function getTitle($ISBN)
  {
    $registedClosure = IoC::resolve('Book_getTitle');
    return $registedClosure($ISBN);
  }
}

Quite simple, right ? Now you can use IoCBook::getTItle($ISBN) instead as below

<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . 'IoCRegister.php';
class Library{
  public function overview()
  {
    $book = IoCBook::getTitle($ISBN);
    return $book;
  }
}

Why I need all that things ?

The idea of IoC help us solve many problem like remove dependencies in codes, remove duplication, etc.. With me it make sense especially in unittesting, where sometimes I have to face with some evil-static-call in classes.

In PHPUnit it's never easy to deal with static methods. Static methods are just death to testability, and PHPUnit have the capablility of mocking static methods where caller and callee are in the same class.

How about when caller and callee in seperated classes ? With IoC implemented, I will help you to overcome that headache in a few basic steps :)

Check out one-minute tutorial !

Bitdeli Badge