电缆/电缆容器

CableFramework 容器组件

1.2.8 2017-06-27 16:04 UTC

README

CableFramework 服务容器

创建新实例

$container = \Cable\Container\Factory::create();

添加新服务

// you can give an anonymous function
$container->add('test', function(){
  return new Test();
});

// you can give the name of class

$container->add('test', Test::class);


// you can give the already exists class instance

$container->add('test', new Test());

解析服务

$test = $container->resolve('test');

// you can give arguments,
// they will be used in constructor calling,
// of course if you didnt give an instance 


$test->resolve('test', array('message' => 'hello world'));

期望

//you may want to check resolved value is an instance of something
// well you can to that like that

$resolved= $container->resolve('test');

if(!$resolved instanceof MyTestInterface){

}

// the problem that you may want to check multipile interfaces
// well, you can do that like that

try{

// you can always give an array like, expect('test', [MyInterface::class, MySecondInterface::class]);
$container->expect('test', MyTestInterface::class);
}catch(ExpectationException $e){
  echo "give me something valid";
}
// if test doesnot return an instanceof MyTestInterface
// container will throw an expectation exception

服务提供者

class Provider extends ServiceProvider{
   public function register(){}
   public function boot(){
     $this->getContainer()->add('test', Test::class);
   }
}

$container = \Cable\Container\Factory::create();

$container->addProvider(Provider::class);


// now you can resolve the 'test' service

$test = $container->resolve('test');

标签

$container->tag([Deneme::class, Test::class], 'test');


list($deneme, $test) = $container->tagged('test');

使用注解

提供者注解

您可以将 @Provider 注解放入类注释文档中

当您尝试解析该类时,将触发 @Provider

/**
 *
 * @Provider("Your\Provide\Class")
 * // you can give multiple providers like @Provider({"FirstProviderClass", "SecondProviderClass"})
 */
class TestClass{


}

注入注解

您可以将 @Inject 注解放入任何方法中

use Cable\Container\Annotations\Inject;

$container->add("my_alias_to_resolve", function(){
      return "hello world";
});


class TestClass{
    
    
    /**
     *
     * @Inject({"$test": "my_alias_to_resolve"})
     *
     */
    public function __construct($test){
    
    }
    
}

与 ; 相同

$container->when(Test::class)
          ->needs("test")
          ->give(function(){
              return $this->getContainer()->make("my_alias_to_resolve");
          });