简单的PSR-11依赖注入容器

v1.2.0 2023-11-11 12:06 UTC

This package is auto-updated.

Last update: 2024-09-24 19:49:29 UTC


README

简单的PSR-11依赖注入容器。

通过Composer安装

您可以使用Composer安装sportlog/di。

$ composer require sportlog/di

所需的最低PHP版本是8。

如何使用

<?php

require 'vendor/autoload.php';

use Sportlog\DI\Container;

// Given this class and interface:
interface FooInterface
{
    public function getFoo(): string;
}

class Foo implements FooInterface
{
    public function __construct(private ?string $foo = 'foo')
    {
    }

    public function getFoo(): string
    {
        return $this->foo;
    }
}

// 1) You can simply get the instance via class id
$container = new Container();
$foo = $container->get(Foo::class);
echo $foo->getFoo();    // outputs: "foo"

// 2) When working with interfaces you must set
// the class id which shall be created
$container = new Container();
$container->set(FooInterface::class, Foo::class);
$foo = $container->get(FooInterface::class);
echo $foo->getFoo();    // outputs: "foo"

// 3) You can also use a factory. Parameters are
// getting injected
class Config
{
    public function getFooInit(): string
    {
        return 'init-foo';
    }
}

$container = new Container();
// Instance of Config will be injected to the factory
$container->set(
    FooInterface::class,
    fn (Config $config) => new Foo($config->getFooInit())
);
$foo = $container->get(FooInterface::class);
echo $foo->getFoo();    // outputs: "init-foo"