dkx/method-injector

This package is abandoned and no longer maintained. No replacement package was suggested.

Inject classes into methods

0.0.1 2019-02-03 13:16 UTC

This package is auto-updated.

Last update: 2024-01-29 03:20:37 UTC


README

Inject classes into methods...

Installation

$ composer require dkx/method-injector

Basic usage

Prepare injector:

<?php

use DKX\MethodInjector\MethodInjector;

$injector = new MethodInjector;

Call method:

<?php

class Foo
{
    public function bar(\stdClass $baz): void { /* ... */ }
}

$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod([new Foo, 'bar']);

Static methods are also supported.

Call static method:

<?php

class Foo
{
    public static function bar(\stdClass $baz): void { /* ... */ }
}

$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod([Foo::class, 'bar']);

provideValue()

This is the simplest method where you say which class to create for which name.

provideFactory()

If you want to customize or create the instance of class lazily this method can be used.

<?php

use DKX\MethodInjector\InjectionContext;

$injector->provideFactory(\stdClass::class, function(InjectionContext $ctx) {
    return new \stdClass;
});

Provide parent class

By default only the exact name of class passed as a first argument of provide*() methods is used when matching called methods. That means that the following example wouldn't work.

<?php

class ParentClass {}
class ChildClass extends ParentClass {}

class Foo
{
    public function bar(ChildClass $child): void { /* ... */ }
}

$injector->provideValue(ParentClass::class, new ParentClass);
$injector->callMethod([new Foo, 'bar']);    // throws exception

To make above code work just change the provideValue() call a bit:

<?php
use DKX\MethodInjector\Providers\Provider;

$injector->provideValue(ParentClass::class, new ParentClass, [
    Provider::USE_FOR_CHILD => true,
]);

With that the MethodInjector will look if ChildClass is subclass of ParentClass. Same will work for interfaces.

Skip static arguments

If your method accepts some static arguments which never changes, you can just pass them into the callMethod method.

<?php

class Foo
{
    public function bar(int $a, string $b, \stdClass $c): void { /* ... */ }
}

$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod(new Foo, 'bar', [42, 'hello world']);

Now in $a will be 42, in $b hello world and in $c instance of stdClass.

Get injectable types

If you only want to know what parameters will be injected, you could use the inferParametersFromMethod method:

<?php

class Foo
{
    public function bar(\stdClass $a, \DateTimeImmutable $b): void { /* ... */ }
}

$injector->provideValue(\stdClass::class, new \stdClass);
$injector->provideValue(\DateTimeImmutable::class, new \DateTimeImmutable);
$inject = $injector->inferParametersFromMethod(Foo::class, 'bar');