Pimpl是php社区中比较流行的容器。代码不是很多,详见 https://github.com/silexphp/Pimple
一个基于Pimple开发简单的例子:
- 创建应用
namespace Always\TencentIm; use Pimple\Container; / * Class TencentIm * @author always <@.com> * * @property \Always\TencentIm\service\Account $account */ class TencentIm extends Container {
/ * Service Providers. * 服务提供者列表 * @var array */ protected $providers = [ ServiceProviders\AccountServiceProvider::class, ]; / * TencentIm constructor. */ public function __construct($config) {
parent::__construct(); // 通用配置,可提供给服务初始化使用 $this['config'] = $config; $this->registerProviders(); } / * 注册服务提供者 * @param array $providers */ public function registerProviders() {
foreach ($this->providers as $provider) {
parent::register(new $provider()); } } / * Magic get access. * * @param string $id * * @return mixed */ public function __get($id) {
return $this->offsetGet($id); } / * Magic set access. * * @param string $id * @param mixed $value */ public function __set($id, $value) {
$this->offsetSet($id, $value); } }
- 创建服务提供者
namespace Always\TencentIm\ServiceProviders; use Pimple\Container; use Pimple\ServiceProviderInterface; use Always\TencentIm\service\Account; class AccountServiceProvider implements ServiceProviderInterface {
public function register(Container $pimple) {
!isset($pimple['account']) && $pimple['account'] = function ($pimple) {
// 服务使用了初始化传入的配置信息 return new Account($pimple['config']); }; } }
服务提供者是连接容器与具体功能实现类的桥梁。服务提供者需要实现接口ServiceProviderInterface
所有服务提供者必须实现接口 register 方法,AccountServiceProvider服务提供者的注册方法会给容器增加属性account,但是返回的不是对象,而是一个闭包
- 应用使用
$config = []; $app = new TencentIm($config); $account = $app->account;
这样就可以使用\Always\TencentIm\service\Account $account对象的方法了。
TencentIm构造函数需要使用 $this->registerProviders(); 对服务提供者进行了注册
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/223799.html原文链接:https://javaforall.net
