php 方法中的依赖注入不起作用

php dependency injection in method not working

我正在尝试通过类型提示在方法中使用依赖注入。它不适合我。调用 $container->get(Name::class); 有效

  if (false === file_exists(__DIR__ . '/../vendor/autoload.php')) {
            die('Install the composer dependencies');
        }
        
        require __DIR__ . '/../vendor/autoload.php';
        
        
        //(new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');
        
        /* Load external routes file */
        require_once dirname(__DIR__) . '/config/routes.php';
        
        $builder = new DI\ContainerBuilder();
        $builder->addDefinitions(dirname(__DIR__) . '/config/Definitions.php');
        try {
            $builder->useAutowiring(true);
            $container = $builder->build();
        } catch (Exception $e) {
            die($e->getMessage());
        }
        
        function test(Cache $cache)
        {
            dd($cache);
        }
        test();
        
        die;

定义文件

<?php

declare(strict_types = 1);

use Psr\Container\ContainerInterface;

require dirname(__DIR__) . '/config/config.php';

return [
    Cache::class => DI\create(Cache::class)->constructor(MEMCACHED_SERVERS),
    
    \Twig\Environment::class => function () {
        $loader = new \Twig\Loader\FilesystemLoader(dirname(__DIR__) . '/Views/');
        $twig = new \Twig\Environment($loader, [
            'cache' => dirname(__DIR__) . '/Cache/'

        ]);

        return $twig;
    },

];

我遇到的错误:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed

那是因为你让 test 函数需要 Cache 然后当你 运行 test() 你不在此处注入 Cache 对象:

function test(Cache $cache)
{
    dd($cache);
}

// here you need to pass instance of Cache
test();

我不熟悉这个代码库,但是你要么需要一个基于反射的自动注入脚本,或者你有什么,来做那个自动注入,要么你需要手动传递 Cache对象:

test(new Cache);

如果 Cache 对象使用所有静态方法或 class 常量,您不需要将其创建为可注入的,您只需在需要的地方使用它,就像在 Cache::class;

最后一种可能性是 $cache 在其中一个文件的某个地方的某些 include 中可用,虽然我在任何地方都看不到它,但如果它可用,你可以制作一个test() 变量函数 use():

$test = function() use ($cache)
{
    dd($cache);
};

// No injection needed
$test();