tmont / blueshift
简单的 inversion of control 容器
1.1.0
2014-01-22 23:25 UTC
Requires
- tmont/phroxy: 1.1.0
Requires (Dev)
- phpunit/phpunit: 3.7.*
This package is not auto-updated.
Last update: 2024-09-24 06:01:16 UTC
README
一个简单的 inversion-of-control 容器。
安装
使用 composer 进行安装
{
"require": {
"tmont/blueshift": "1.1.*"
}
}
Blue Shift 符合 PSR-4 标准,因此一旦您执行了 composer install,以下设置将自动加载
require_once 'vendor/autoload.php';
使用方法
一些示例对象
interface MyInterface {} class MyType implements MyInterface { public function __construct(MyOtherType $type) { $this->type = $type; } } class MyOtherType { public function __construct($foo) { $this->foo = $foo; } }
注册类型和实例
$container = new Tmont\BlueShift\Container(); $container ->registerType('MyType', 'MyType') ->registerInstance('MyOtherType', new MyOtherType('bar')); $myType = $container->resolve('MyType'); echo $myType->type->foo; // 'bar'
注册映射类型(接口 -> 实现)
$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
使用 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!'
容器也可以解析您给出的任何内容,即使您没有显式创建映射,只要类型可实例化即可。
class Nope { private function __construct() {} } class Yup {} $container = new Tmont\BlueShift\Container(); $container->resolve('Yup'); //no probalo $container->resolve('Nope'); //throws InvalidConstructorException
开发
git clone git@github.com:tmont/blueshift.git
cd blueshift
composer install
vendor/bin/phpunit