tmont/blueshift

Simple inversion of control container

1.1.0 2014-01-22 23:25 UTC

This package is not auto-updated.

Last update: 2024-04-09 03:44:44 UTC


README

Build Status

A simple inversion-of-control container.

Installation

Install using composer:

{
  "require": {
    "tmont/blueshift": "1.1.*"
  }
}

Blue Shift is PSR-4 compliant, so the following will setup autoloading once you've composer install'd:

require_once 'vendor/autoload.php';

Usage

Some example objects:

interface MyInterface {}

class MyType implements MyInterface {
  public function __construct(MyOtherType $type) {
    $this->type = $type;
  }
}

class MyOtherType {
  public function __construct($foo) {
    $this->foo = $foo;
  }
}

Registering a type and an instance:

$container = new Tmont\BlueShift\Container();
$container
  ->registerType('MyType', 'MyType')
  ->registerInstance('MyOtherType', new MyOtherType('bar'));

$myType = $container->resolve('MyType');
echo $myType->type->foo; // 'bar'

Registering a mapped type (interface -> implementation):

$container = new Tmont\BlueShift\Container();
$container
  ->registerType('MyInterface', 'MyType')
  ->registerInstance('MyOtherType', new MyOtherType('bar'));

$myType = $container->resolve('MyInterface');
echo $myType instanceof MyInterface; // true
echo $myType instanceof MyClass; // true

Proxies and interception using Phroxy:

use Tmont\Phroxy\Interceptor;
use Tmont\Phroxy\InterceptionContext;

class MyInterceptableClass {
	public function foo() {
		return 'intercepted!';
	}
}

class MyInterceptor implements Interceptor {
	public function onBeforeMethodCall(InterceptionContext $context) {
		$context->setReturnValue('not foo');
	}

	public function onAfterMethodCall(InterceptionContext $context) {}
}

$container = new Tmont\BlueShift\Container();
$container
  ->registerType('MyInterceptableClass', 'MyInterceptableClass')
  ->proxyType('MyInterceptableClass')
  ->registerInterceptor(new MyInterceptor(), function(ReflectionMethod $method) {
	    return $method->getDeclaringClass()->getName() === 'MyInterceptableClass' &&
	        $method->getName() === 'foo';
    });

$obj = $container->resolve('MyInterceptableClass');
echo $obj->foo(); // 'intercepted!'

The container can also resolve anything you give it, even if you don't explicitly create a mapping, provided the type is instantiable.

class Nope {
	private function __construct() {}
}

class Yup {}

$container = new Tmont\BlueShift\Container();
$container->resolve('Yup'); //no probalo
$container->resolve('Nope'); //throws InvalidConstructorException

Development

git clone git@github.com:tmont/blueshift.git
cd blueshift
composer install
vendor/bin/phpunit