codelego/phpfox-service

phpfox框架的服务库。

dev-master 2016-11-29 10:44 UTC

This package is not auto-updated.

Last update: 2024-09-28 19:58:06 UTC


README

此库不支持服务定位模式。
所有服务必须在配置中显式声明。

服务管理器是一个容器,它通过名称而不是显式创建来控制对象的创建方式。

容器中有4种方法

  • has($id): bool
  • get($id): mixed
  • set($id, $object)
  • build($id): mixed
  • remove($id): void

为了配置对象,请在module.config.php中声明它们。

return [
    'services'=>[
        'map'=>[
            'db'=> [null, ServiceClass],
            'db2'=> [ServiceFactoryClass,],
        ]
    ]
]

我们支持两种$scheme值的表示方式

  • 如果第一个值是null,则将调用ServiceClass的构造函数。
  • 如果第一个值是字符串,则必须实现FactoryInterface,因此将使用工厂模式。

示例

module.config.php

return [
    'services'=>[
        'map'=>[
            'models'=>[null, 'Phpfox\Model\GatewayManager'],
            'other_service'=> [OtherServiceFactory,]
        ]
    ]
]

class OtherServiceFactory {
    function factory($className){
        return new ExampleService();
    }
}

直接使用类名

$models  =  $service->get('models');
echo get_class($models);
//print "Phpfox\Model\GatewayManager"

使用工厂类名

$others  =  $service->get('other_service');
echo get_class($others);
//print "ExampleService"

服务管理器是一个容器,当你调用get($id)

  • 如果是第一次调用,它们会为$id构建一个服务映射,然后将其存储在容器中。
  • 再次调用get($id),它将返回容器中的对象。
  • 如果你想创建一个新的$id实例,请调用build($id)代替。