fas/autowire

快速且简单的自动装配

0.2.2 2021-07-18 21:33 UTC

This package is auto-updated.

Last update: 2024-09-19 04:28:08 UTC


README

Build Status Test Coverage

Latest Stable Version Latest Unstable Version License Total Downloads

安装

composer require fas/autowire

简介

此库通过任何PSR-11容器引入自动装配功能。此库还提供了一个非常简单的容器。

使用方法

创建对象

require __DIR__ . '/../vendor/autoload.php';

use Fas/Autowire/Autowire;

$autowire = new Autowire();

// Autowire all constructor arguments
$myObject = $autowire->new(MyClass::class);

// Override some constructor arguments
$myObject = $autowire->new(MyClass::class, ['some_argument' => 'test-value']);

// Call a method with no arguments (autowire all arguments)
$autowire->call(function (DateTime $datetime, MyClass $myObject) {
    // do stuff
});

// Override argument
$autowire->call(function (DateTime $datetime, MyClass $myObject) {
    // do stuff
}, ['datetime' => new DateTime('2021-07-01 12:34:56')]);

// Any callable will do
// Plain function
$upperCased  = $autowire->call('strtoupper', ['str' => 'something-in-lower-case']);

// Static method
$datetime = $autowire->call([DateTime::class, 'createFromFormat'], [
    'format' => 'Y-m-d H:i:s',
    'time' => '2021-01-02 12:34:56', // php7
    'datetime' => '2021-01-02 12:34:56', // php8
    'object' => new DateTimeZone('Europe/Copenhagen'),
]);

// Instance method
$autowire->call([new DateTime, 'setTime'], ['hour' => 0, 'minute' => 1, 'second' => 2, 'microseconds' => 123]);

// Invokable class
$autowire->call($myInvokableClass, ['my_param' => 'test']);

为任何psr-11容器使用自动装配

$container = new MyPsrContainer();
$autowire = new Autowire($container);

使用fas/autowire容器

$container = new Container();
$container->set(LoggerInterface::class, NullLogger::class);

$autowire = new Autowire($container);
$autowire->call(function (LoggerInterface $logger) {
    $logger->info("Logging using whatever logger is defined for LoggerInterface in the container");
});