yiisoft/definitions 问题修复 & 功能扩展

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

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

yiisoft/definitions

Composer 安装命令:

composer require yiisoft/definitions

包简介

The package provides definition syntax

关键字:

README 文档

README

Yii

Yii Definitions


Latest Stable Version Total Downloads Build status Code Coverage Mutation testing badge Static analysis type-coverage

The package provides syntax constructs describing a way to create and configure a service or an object. It is used by yiisoft/di and yiisoft/factory but could be used in other PSR-11 compatible packages as well.

The following are provided:

  • Definitions describing services or objects to create. This includes syntax, its validation and resolving it to objects.
  • References and dynamic references to point to other definitions. These include additional utility to refer to multiple definitions at once.

Requirements

  • PHP 8.1 - 8.5.

Installation

The package could be installed with Composer:

composer require yiisoft/definitions

General usage

Definitions

Definition is describing a way to create and configure a service, an object or return any other value. It must implement Yiisoft\Definitions\Contract\DefinitionInterface that has a single method resolve(ContainerInterface $container). References are typically stored in the container or a factory and are resolved into an object at the moment of getting a service instance or creating an object.

ArrayDefinition

Array definition allows describing a service or an object declaratively:

use \Yiisoft\Definitions\ArrayDefinition;

$definition = ArrayDefinition::fromConfig([
    'class' => MyServiceInterface::class,
    '__construct()' => [42], 
    '$propertyName' => 'value',
    'setName()' => ['Alex'],
]);
$object = $definition->resolve($container);

In the above:

  • class contains the name of the class to be instantiated.
  • __construct() holds an array of constructor arguments.
  • The rests of the config are property values (prefixed with $) and method calls, postfixed with (). They are set/called in the order they appear in the array.

For multiple method call postfix key with unique string, for example:

[
    'class' => Collector::class,
    'add()' => ['Alex'],
    'add()2' => ['Mike'],
]

CallableDefinition

Callable definition builds an object by executing a callable injecting dependencies based on types used in its signature:

use \Yiisoft\Definitions\CallableDefinition;

$definition = new CallableDefinition(
    fn (SomeFactory $factory) => $factory->create('args')
);
$object = $definition->resolve($container);

// or 

$definition = new CallableDefinition(
    fn () => MyFactory::create('args')
);
$object = $definition->resolve($container);

// or

$definition = new CallableDefinition(
    [MyFactory::class, 'create']
);
$object = $definition->resolve($container);

In the above, we use a closure, a static call and a static method passed as array-callable. In each case, we determine and pass dependencies based on the types of arguments in the callable signature.

ParameterDefinition

Parameter definition resolves an object based on information from ReflectionParameter instance:

use \Yiisoft\Definitions\ParameterDefinition;

$definition = new ParameterDefinition($reflectionParameter);
$object = $definition->resolve($container);

It is mostly used internally when working with callables.

ValueDefinition

Value definition resolves value passed as is:

use \Yiisoft\Definitions\ValueDefinition;

$definition = new ValueDefinition(42, 'int');
$value = $definition->resolve($container); // 42

References

References point to other definitions, so when defining a definition, you can use other definitions as its dependencies:

[
    InterfaceA::class => ConcreteA::class,
    'alternativeForA' => ConcreteB::class,
    MyService::class => [
        '__construct()' => [
            Reference::to('alternativeForA'),
        ],
    ],
]

Optional reference returns null when there's no corresponding definition in container:

[
    MyService::class => [
        '__construct()' => [
            // If a container doesn't have definition for `EventDispatcherInterface` reference returns `null`
            // when resolving dependencies
            Reference::optional(EventDispatcherInterface::class), 
        ],
    ],
]

The DynamicReference defines a dependency to a service not defined in the container:

[
   MyService::class => [
       '__construct()' => [
           DynamicReference::to([
               'class' => SomeClass::class,
               '$someProp' => 15
           ])
       ]
   ]
]

To pass an array of IDs as references to a property or an argument, Yiisoft\Definitions\ReferencesArray or Yiisoft\Definitions\DynamicReferencesArray could be used:

//params.php
return [
   'yiisoft/data-response' => [
       'contentFormatters' => [
           'text/html' => HtmlDataResponseFormatter::class,
           'application/xml' => XmlDataResponseFormatter::class,
           'application/json' => JsonDataResponseFormatter::class,
       ],
   ],
];

//web.php

ContentNegotiator::class => [
    '__construct()' => [
        'contentFormatters' => ReferencesArray::from($params['yiisoft/data-response']['contentFormatters']),
    ],
],

Class aliases

To define another instance of a class with specific configuration, you can use native PHP class_alias():

class_alias(Yiisoft\Db\Pgsql\Connection::class, 'MyPgSql');

return [
    MyPgSql::class => [ ... ]
];

Definition storage

Definition storage could be used to hold and get definitions and check if a certain definition could be instantiated. Usually it is used by an implementation using the definitions:

use Yiisoft\Definitions\DefinitionStorage;

$storage = new DefinitionStorage([
    MyInterface::class => MyClass::class,
]);
$storage->setDelegateContainer($fallbackContainer);

if (!$storage->has(MyInterface::class)) {
    $buildStack = $storage->getBuildStack();
    // ...
}

In the above $buildStack will contain a stack with definition IDs in the order the latest dependency obtained would be built.

By default, if a class is checked in has() and it is not explicitly defined, the storage tries to autoload it first before failing. The storage may also work in a strict mode when everything in it should be defined explicitly:

use Yiisoft\Definitions\DefinitionStorage;

$storage = new DefinitionStorage([], true);
var_dump($storage->has(EngineMarkOne::class));

has() will return false even if EngineMarkOne exists.

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii Definitions is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yiisoft/definitions 适用场景与选型建议

yiisoft/definitions 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.36M 次下载、GitHub Stars 达 15, 最近一次更新时间为 2021 年 08 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 yiisoft/definitions 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.36M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 15
  • 点击次数: 18
  • 依赖项目数: 49
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 13
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2021-08-27