jesusslim/pinject

在PHP中进行注入

1.2.3 2017-05-26 06:47 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:31:13 UTC


README

在PHP中注入!

使用方法

[英文] 中文

安装

在Packagist上安装pinject:https://packagist.org.cn/packages/jesusslim/pinject

安装

composer require jesusslim/pinject

如果你的composer不允许dev-master,请添加以下配置到你的composer.json中。

"minimum-stability": "dev"

配置

注入器

InjectorInterface声明了一些用于注入的功能,例如

map //map a concrete or class or object or closure to the inject container
get //get things your mapped
produce //produce concrete

Injector类实现了InjectorInterface。创建一个需要使用注入功能的类,并使其继承自Injector类。然后使用这些功能

//map a data or object
$injector->mapData('test',12345);
$injector->mapData(Student::class,new Student('Slim'));

//map a class
$injector->mapSingleton(StudentInterface::class,GoodStudent::class);

//produce
//if the key is found in mapped data,objects,it will return the things we mapped.
//if the key is found in mapped classes,it will check if this class is been produced,if it's been produced,it return the concrete that produced before,else return a new concrete of this class.
//if this key not found in any map,it will try to reflect this class unless we use the function mustReg() to make sure all the things can be produced should be mapped first.
$injector->produce(StudentInterface::class);

//call an function
//it will fill the paramters of this function with the concrete produced by pinject.
$injector->call(function(Student $std){
	...
});

//call an function in class
//it will call a function in class.it will try to find the class from pinject if it has been produced or reflect it.and fill the paramters with concrete produced by pinject.
$injector->callInClass($class_name,$action,$out_params);

链式操作

我们可以使用链式操作来完成一些链式操作。

示例

$chains = new Chains($app);
//here $app is an Injector
$chains->chain(RequestHandler::class)
->chain(function($data,$next){
    $r = Auth::checkToken($data['token']);
    if($r !== true){
        dump("Token wrong");
    }else{
        $next($data);
    }
})
->chain(Student::class)
->chain(function($data){
    dump($data);
})
->action('handle')
->run();
//or use runWith($your_last_chain_func);

我们可以在链中链入一个闭包或一个类。如果是一个类,它将调用名为'handle'的方法。每个用于handle的闭包或方法应该有两个参数:链中传递的数据和下一个处理器。在每个链的末尾,如果成功,我们应该调用下一个处理器。

另一种使用链的方式

另一种使用链的方式是使用runWild代替run/runWith,它更类似于golang中Martini/Injector的使用。

示例

$chains = new \Inject\Chains($app);
$app->mapData('any_param_here','Example');
$the_given_params_for_handlers = [
	'seems_wild' => 'OK'
];
$rtn = $chains->chain(function($any_param_here,$seems_wild){
	var_dump($any_param_here.' is '.$seems_wild);
})->chain(function(){
	return "END";
})->data($the_given_params_for_handlers)
->runWild();
var_dump($rtn);

正如我们所看到的,runWild和run/runWith之间的区别在于,runWild支持任何类型的处理器,并且任何处理器返回的结果都将终止循环并返回结果。