crodas/service-provider

小型配置管理器和依赖注入

v0.1.32 2015-12-21 23:23 UTC

README

小型配置管理器和依赖注入。

它是一个尝试构建一个简单的库来定义服务,以及如何消费它们的尝试。一个 服务 是一个可配置的资源,它被我们的软件使用,想想看,就像一个 mysql_connect 资源,你可以为本地和生产环境配置不同的设置。

可以使用注解来定义服务。

/**
 *  @Service(mysql, {
 *    host: {default:"localhost", type: string},
 *    user: {default:"root", type: string},
 *    pass: {default:"", type: string},
 *    port: {default: 3306, type: integer},
 *    db: {type: string},
 *  })  
 */
function get_mysql_service(Array $config)
{
    return new mysqli(
      $config['host'], 
      $config['user'], 
      $config['pass'], 
      $config['db'],
      $config['port']
    );
}

就是这样,我们只定义了一个服务,实际上它是一个返回某些内容的函数或方法。在其注解中,我们定义了其名称及其配置验证。

当你想要访问mysql服务时

$service = new \ServiceProvider\Provider(
  'production.config.yml',  // the configuration file
  'where/services/are/defined/',  // where the files are defined.  It can use * comodin
  'production.generated.php' // to improve things we generate code, here is where to save it
);
$db = $service->get('mysql');
$db->query("SELECT * FROM users");

事件

作为额外的好处,这个库支持正确的事件触发/处理。基本上,在生成时间,它会查找方法或函数上的 @EventSubscriber(<name>, [<preference>=0])。触发一个事件非常简单

$service = new \ServiceProvider\Provider(
  'production.config.yml',  // the configuration file
  'where/services/are/defined/',  // where the files are defined.  It can use * comodin
  'production.generated.php' // to improve things we generate code, here is where to save it
);

$events = $service->get('event_manager');
$result = $events->trigger('foo.bar', array('arg1' => 'foo'));
var_dump('this event had ' . $result->getCalls() . ' handlers');

并在代码的某个地方

/**
 *  @EventSubscriber(foo.bar)
 */
function some_handler($event)
{
    $args = $event->getArguments();
    $event->stopPropagation(); /* I'm the last one */
}