decodelabs/slingshot

Unified dependency injection invoker

v0.1.11 2024-08-22 01:10 UTC

This package is auto-updated.

Last update: 2024-11-04 21:53:09 UTC


README

PHP from Packagist Latest Version Total Downloads GitHub Workflow Status PHPStan License

Unified dependency injection invoker

Slingshot provides a simple interface for invoking methods on objects with dependency injection.

Get news and updates on the DecodeLabs blog.

Installation

Install via Composer:

composer require decodelabs/slingshot

Usage

Use a Slingshot instance to invoke a function with dependency injection:

use DecodeLabs\Slingshot;

$slingshot = new Slingshot(
    container: $container, // Psr\Container\ContainerInterface
    parameters: [
        'param1' => 'hello'
    ]
);

function test(
    string $param1,
    string $param2
) {
    return $param1 . ' '. $param2;
}

$output = $slingshot->invoke(test(...), [
    'param2' => 'world'
]); // hello world

Or instantiate an object with dependency injection:

use DecodeLabs\Harvest\Context as HarvestContext;

class Test {
    public function __construct(
        // Fetch or create a Harvest Context (example) from container
        HarvestContext $param1,
        string $param2
    ) {
        // ...
    }
}

$testObect = $slingshot->instantiate(Test::class, [
    'param2' => 'value'
]);

Objects can be added to Slingshot by type for reference matching:

$object = new Test(...);
$slingshot->addType($object);

$slingshot->invoke(function(Test $test) {
    // ...
});

Licensing

Slingshot is licensed under the MIT License. See LICENSE for the full license text.