PHP 依赖注入解析具有原始依赖的类

PHP Dependency Injection resolving class with primitive dependencies

提问人:Kristian Vasilev 提问时间:8/10/2023 更新时间:8/10/2023 访问量:53

问:

我认为我在尝试编写自己的依赖注入容器时做错了什么。我正在看 laravel 的那个,它在评论中说

// If the class is null, it means the dependency is a string or some other
// primitive type which we can not resolve since it is not a class and
// we will just bomb out with an error since we have no-where to go.

以及用于解析类依赖关系的代码:

protected function resolveDependencies(array $dependencies)
{
    $results = [];

    foreach ($dependencies as $dependency) {
        // If the dependency has an override for this particular build we will use
        // that instead as the value. Otherwise, we will continue with this run
        // of resolutions and let reflection attempt to determine the result.
        if ($this->hasParameterOverride($dependency)) {
            $results[] = $this->getParameterOverride($dependency);

            continue;
        }

        // If the class is null, it means the dependency is a string or some other
        // primitive type which we can not resolve since it is not a class and
        // we will just bomb out with an error since we have no-where to go.
        $result = is_null(Util::getParameterClassName($dependency))
                        ? $this->resolvePrimitive($dependency)
                        : $this->resolveClass($dependency);

        if ($dependency->isVariadic()) {
            $results = array_merge($results, $result);
        } else {
            $results[] = $result;
        }
    }

    return $results;
}

这是我对此类的实现: 链接到代码

所以我有以下问题:

  1. 如果我的构造函数中有基元类型,我该怎么办?例如: 但这里实际上是具有以下依赖关系的:public function __construct(ServerConfig $config, RequestInterface $request)$requestGuzzleHttp\Psr7\Request

public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1') {}

  1. 我应该 DI 没有基元类型的类吗?
  2. 如果我有一个 A 类,它需要 B 类作为 DI,但 B 类依赖于 C 类,它有一些基元类型,会发生什么?
PHP的 拉拉维尔 依赖注入 基元类型

评论

0赞 mrhn 8/10/2023
这与Laravel有什么关系,因为Laravel已经有一个容器了?

答: 暂无答案