此项目是我作品集的示例。Container 是依赖注入容器。它允许您实现依赖注入设计模式,意味着您可以解耦您的类依赖,并将它们注入到需要的地方。

1.0.0 2023-05-19 12:53 UTC

This package is auto-updated.

Last update: 2024-09-19 15:29:40 UTC


README

此项目是我作品集的示例。Container 是依赖注入容器。它允许您实现依赖注入设计模式,意味着您可以解耦您的类依赖,并将它们注入到需要的地方。

全球使用情况

您的代码

<?php

class Сooker implements СookerInterface
{
    // some code
}

class Fridge implements FridgeInterface
{
    // some code
}

class Kitchen
{
    public function __construct(
        protected СookerInterface $cooker,
        protected FridgeInterface $fridge,
        protected int $area,
        )
    {      
    }

    public function getArea(): int
    {
        return $this->area;
    }
}

使用DIContainer注入依赖

<?php

use Container\Container;

$container = new Container();

$container->add('kitchenArea', 666)->addTag('apartment');

$container->add(СookerInterface::class, 
        fn() => new Сooker()
    )->addTag('apartment');

$container->add(FridgeInterface::class, 
        fn() => new Fridge()
    )->addTag('apartment');

$container->add(Kitchen::class, 
        fn() => new Kitchen(
            $container->get(СookerInterface::class),
            $container->get(FridgeInterface::class),
            $container->get('kitchenArea'),
        )
    )->addTag('apartment');

片刻之后

<?php

if ($container->get(Kitchen::class)->getArea() === 666) {
    echo 'You have successfully injected the dependency!';
}
    You have successfully injected the dependency!

许可证

MIT