Blue Shift
, (*1)
A simple inversion-of-control container., (*2)
Installation
Install using composer:, (*3)
{
"require": {
"tmont/blueshift": "1.1.*"
}
}
Blue Shift is PSR-4 compliant, so the following will setup autoloading once
you've composer install
'd:, (*4)
require_once 'vendor/autoload.php';
Usage
Some example objects:, (*5)
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:, (*6)
$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):, (*7)
$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:, (*8)
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., (*9)
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