yhs-hyperf-helper/dependency

dev-main 2024-06-28 06:42 UTC

This package is auto-updated.

Last update: 2024-09-28 09:14:50 UTC


README

徽章

PHP Composer PHPUnit Release

简介

在Hyperf中添加依赖的简单、直接且优雅的方式

开始

composer require hyperf-helper/dependency

注解参数

如何使用

  1. 我们需要将从 DependencyCollector 收集到的依赖添加到 Container
<?php
# config/container.php

<?php
/**
 * Initialize a dependency injection container that implemented PSR-11 and return the container.
 */

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

use Hyperf\Di\Container;
use Hyperf\Di\Definition\DefinitionSourceFactory;
use Hyperf\Utils\ApplicationContext;

$container = new Container((new DefinitionSourceFactory(true))());

if (! $container instanceof \Psr\Container\ContainerInterface) {
    throw new RuntimeException('The dependency injection container is invalid.');
}

/*********     start      ********/
// Add this line between `new Container` and `setContainer()`
\HyperfHelper\Dependency\Annotation\Collector\DependencyCollector::walk([$container, 'define']);
/*********      end       ********/

return ApplicationContext::setContainer($container);
  1. 使用 Dependency 注解您想要定义的依赖类
declare(strict_types=1);

namespace App\Service;

use HyperfHelper\Dependency\Annotation\Dependency;

// add Dependency annotation
#[Dependency()]
class ExampleService implements ExampleServiceInterface {
    // anything
}
  1. 在各个地方快乐地使用 Inject
<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use App\Service\ExampleServiceInterface;


class FooController {

    #[Inject]
    protected ExampleServiceInterface $service;
}

"# hyperf-helper-dependency"