fas / autowire
Fast and simple autowiring
0.2.2
2021-07-18 21:33 UTC
Requires
- php: >=7.4.0
- fas/exportable: ^0.2
- ocramius/proxy-manager: ^2.11
- opis/closure: ^3.6
- psr/container: ^1.0 || ^2.0
- psr/log: ^1.1
Requires (Dev)
- phpmd/phpmd: ^2.10
- phpunit/phpunit: ^9
- squizlabs/php_codesniffer: ^3.6
Provides
README
Installation
composer require fas/autowire
Introduction
This library introduces autowiring capabilities using any PSR-11 container. A very simple container is also provided with this library.
Usage
Create object
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']);
Using Autowiring for any psr-11 container:
$container = new MyPsrContainer(); $autowire = new Autowire($container);
Using the fas/autowire container
$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"); });