phpwatch/simple-container 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

phpwatch/simple-container

Composer 安装命令:

composer require phpwatch/simple-container

包简介

A fast and minimal PSR-11 compatible Dependency Injection Container with array-syntax and without auto-wiring

README 文档

README

A fast and minimal PSR-11 compatible Dependency Injection Container with array-syntax and without auto-wiring.

Latest Stable Version CI codecov Scrutinizer Code Quality License

Design goals

  • Do one thing and do it well
  • ~100 LOC
  • No auto-wiring by design
  • Services are declared as closures
  • Array-syntax to access and set services ($container['database'])
  • Fully PSR-11 compliant
  • Support for protected services (return closures verbatim)
  • Support for factory services (return a new instance instead of returning the same instance)
  • 100% test coverage
  • Services can over overwritten later, marked factory/protected
  • Function at full speed without a compilation step

Installation

composer require phpwatch/simple-container

Usage

Simple Container supports array-syntax for setting and fetching of services and values. You can mark certain services as factory or protected later too.

Declare services and values

<?php
use Psr\Container\ContainerInterface;

$container = new PHPWatch\SimpleContainer\Container();  
  
$container['database.dsn'] = 'mysql:host=localhost;database=test';  
$container['database'] = static function(ContainerInterface $container): \PDO {  
 return new \PDO($container->get('database.dsn'));  
};
$container['api.ipgeo'] = 'rhkg3...';

Fetch services

Do not use this class as a service locator. The closures you declare for each service will get the Container instance, from which you can fetch services using the array syntax:

<?php  
$container['database']; // \PDO  
// OR  
$container->get('database'); // \PDO  

Create container from definitions

<?php
use Psr\Container\ContainerInterface;  
use PHPWatch\SimpleContainer\Container;  
  
$services = [  
    'database' => [
        'dsn' => 'sqlite...'  
    ],  
    'prefix' => 'Foo',  
    'csprng' => static function (ContainerInterface $container) {  
        return $container->get('prefix') . bin2hex(random_bytes(16));  
    }
]; 
  
$container = new Container($services);  
$container->get('prefix'); // Foo

Factory and Protected Services

If the service definition is a closure (similar to the database example above), the return value will be cached, and returned for subsequent calls without instantiating again. This is often the use expected behavior for databases and other reusable services.

Factory Services

To execute the provided closure every-time a service is requested (for example, to return an HTTP client), you can use factories.

<?php
$container->setFactory('http.client', static function(ContainerInterface $container) {
	$handler = new curl_init();
	curl_setopt($handler,CURLOPT_USERAGENT, $container->get('http.user-agent'));
	
	return $handler;
};

The example above will always return a new curl handler resource everytime $container->get('http.client') is called, with the User-Agent string set to the http.user-agent value from container.

You can also mark a container service as a factory method later if it's already set:

<?php
$container->setFactory('http.client'); // Mark existing definition as a factory.

If you have already declared the http.client service, it will now be marked as factory. If the existing declaration is not set, or is not a callable, a PHPWatch\SimpleContainer\Exception\BadMethodCallExceptionTest exception will be thrown.

Protected Services

Simple Container expects the service declarations to be closures, and it will execute the closure by itself to return the service. However, in some situations, you need to return a closure itself as the service.

<?php
$container['csprng'] = static function(): string {
	return bin2hex(random_bytes(32));
};

$container['csprng']; // "eaa3e95d4102..."
$container['csprng']; // "eaa3e95d4102..."
$container['csprng']; // "eaa3e95d4102..."

This behavior is probably not what you wanted. You can mark the service as factory to retrieve different values every-time it is called. You can also mark it as protected, which will return the closure itself, so you can call it on your code:

<?php
$container->setProtected('csprng', static function(): string {
	return bin2hex(random_bytes(32));
});

$csprng = $container->get('csprng');

echo $csprng(); // eaa3e95d4102...
echo $csprng(); // b857ce87400b...
echo $csprng(); // a833e3db880...

Extend container

Just use the array syntax and add/remove services

<?php
// Remove:  
unset($container['secret.service']);  
  
// Extend:  
$container['secret.service'] = static function(): void { throw new \Exception('You are not allowed to use this');}  

Freezing container

By design, container is not allowed to be frozen. The Container class is extensible (get, getOffset, or the Container class itself are not declared final) if you absolutely need this feature.

Contributing

You are welcome to raise an issue or a PR if you have any questions or suggestions. Please keep in mind that this container aims to be the simplest and fastest container, and follow SOLID principles. Any feature that steps outside these goals (see design goals above) will likely not be accepted. However, your contributions will be appreciated and considered regardless of their nature.

Credits and Inspiration

This project is inspired by the Pimple project. It is no closed for new features and modifications, and does not support PSR-11. This sparked the idea of this project, and Pimple deserves the credit for its solid architecture and minimal set of features, including the support for array syntax.

Although separate projects, Simple Container is largely compatible with Pimple. This project is used in PHP.Watch and drop-in replaced Pimple.

phpwatch/simple-container 适用场景与选型建议

phpwatch/simple-container 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11.67k 次下载、GitHub Stars 达 18, 最近一次更新时间为 2020 年 05 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「dependency injection」 「container」 「PSR-11」 「psr11」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 phpwatch/simple-container 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 phpwatch/simple-container 我们能提供哪些服务?
定制开发 / 二次开发

基于 phpwatch/simple-container 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 11.67k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 18
  • 点击次数: 10
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 18
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-05-07