Pimple Containter 容器使用实例代码

591 查看

Pimple/Container

安装

composer require "pimple/pimple": "^3.0"

代码

加载并实例化

require __DIR__ . '/vendor/autoload.php';
$pc = new Pimple\Container();

参数存储

$pc['app_id']='pimple';

单例存储

$pc['app']=function($c){
    $app=new stdClass();
    $app->app_id=$c['app_id'];
    return $app;
};
$app_one=$pc['app'];
$app_two=$pc['app'];
var_dump($app_one === $app_two);// true

非单例存储

$pc['api'] = $pc->factory(function ($c) {
    $api=new stdClass();
    $api->app_id=$c['app_id'];
    return $api;
});
$api_one=$pc['api'];
$api_two=$pc['api'];
var_dump($api_two === $api_two);// false

存储匿名函数

$pc['random_func']=$pc->protect(function () {
    return rand();
});

获取匿名函数

$random=$pc->raw('random_func');
var_dump($random());

服务提供者

class UcProvider implements Pimple\ServiceProviderInterface
{
    public function register(Pimple\Container $c)
    {
        $uc_id=6;
        $c['uc_config']=['uc_id'=>$uc_id];
        $c['uc_class']=function ($c) use ($uc_id){
            $uc=new stdClass();
            $uc->id=$uc_id;
            return $uc;
        };
    }
}
$pc->register(new UcProvider());
var_dump($pc['uc_config']);
var_dump($pc['uc_class']);

文档

官网文档 : http://pimple.sensiolabs.org/