项目作者: yiisoft

项目描述 :
The package provides definition syntax. Definition is describing a way to create and configure a service or an object.
高级语言: PHP
项目地址: git://github.com/yiisoft/definitions.git
创建时间: 2021-08-25T21:36:07Z
项目社区:https://github.com/yiisoft/definitions

开源协议:BSD 3-Clause "New" or "Revised" License

下载




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 or higher.

Installation

The package could be installed with Composer:

  1. 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:

  1. use \Yiisoft\Definitions\ArrayDefinition;
  2. $definition = ArrayDefinition::fromConfig([
  3. 'class' => MyServiceInterface::class,
  4. '__construct()' => [42],
  5. '$propertyName' => 'value',
  6. 'setName()' => ['Alex'],
  7. ]);
  8. $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:

  1. [
  2. 'class' => Collector::class,
  3. 'add()' => ['Alex'],
  4. 'add()2' => ['Mike'],
  5. ]

CallableDefinition

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

  1. use \Yiisoft\Definitions\CallableDefinition;
  2. $definition = new CallableDefinition(
  3. fn (SomeFactory $factory) => $factory->create('args')
  4. );
  5. $object = $definition->resolve($container);
  6. // or
  7. $definition = new CallableDefinition(
  8. fn () => MyFactory::create('args')
  9. );
  10. $object = $definition->resolve($container);
  11. // or
  12. $definition = new CallableDefinition(
  13. [MyFactory::class, 'create']
  14. );
  15. $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:

  1. use \Yiisoft\Definitions\ParameterDefinition;
  2. $definition = new ParameterDefinition($reflectionParameter);
  3. $object = $definition->resolve($container);

It is mostly used internally when working with callables.

ValueDefinition

Value definition resolves value passed as is:

  1. use \Yiisoft\Definitions\ValueDefinition;
  2. $definition = new ValueDefinition(42, 'int');
  3. $value = $definition->resolve($container); // 42

References

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

  1. [
  2. InterfaceA::class => ConcreteA::class,
  3. 'alternativeForA' => ConcreteB::class,
  4. MyService::class => [
  5. '__construct()' => [
  6. Reference::to('alternativeForA'),
  7. ],
  8. ],
  9. ]

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

  1. [
  2. MyService::class => [
  3. '__construct()' => [
  4. // If a container doesn't have definition for `EventDispatcherInterface` reference returns `null`
  5. // when resolving dependencies
  6. Reference::optional(EventDispatcherInterface::class),
  7. ],
  8. ],
  9. ]

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

  1. [
  2. MyService::class => [
  3. '__construct()' => [
  4. DynamicReference::to([
  5. 'class' => SomeClass::class,
  6. '$someProp' => 15
  7. ])
  8. ]
  9. ]
  10. ]

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

  1. //params.php
  2. return [
  3. 'yiisoft/data-response' => [
  4. 'contentFormatters' => [
  5. 'text/html' => HtmlDataResponseFormatter::class,
  6. 'application/xml' => XmlDataResponseFormatter::class,
  7. 'application/json' => JsonDataResponseFormatter::class,
  8. ],
  9. ],
  10. ];
  11. //web.php
  12. ContentNegotiator::class => [
  13. '__construct()' => [
  14. 'contentFormatters' => ReferencesArray::from($params['yiisoft/data-response']['contentFormatters']),
  15. ],
  16. ],

Class aliases

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

  1. class_alias(Yiisoft\Db\Pgsql\Connection::class, 'MyPgSql');
  2. return [
  3. MyPgSql::class => [ ... ]
  4. ];

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:

  1. use Yiisoft\Definitions\DefinitionStorage;
  2. $storage = new DefinitionStorage([
  3. MyInterface::class => MyClass::class,
  4. ]);
  5. $storage->setDelegateContainer($fallbackContainer);
  6. if (!$storage->has(MyInterface::class)) {
  7. $buildStack = $storage->getBuildStack();
  8. // ...
  9. }

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:

  1. use Yiisoft\Definitions\DefinitionStorage;
  2. $storage = new DefinitionStorage([], true);
  3. 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