【问题标题】:php dependency injection in method not working方法中的php依赖注入不起作用
【发布时间】:2021-06-18 09:54:25
【问题描述】:

我正在尝试通过类型提示在方法中使用依赖注入。它不适合我。调用$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;
    },

];

我得到的错误:

致命错误:未捕获的 ArgumentCountError:参数太少 函数 test(), 0 通过

【问题讨论】:

    标签: php dependency-injection


    【解决方案1】:

    那是因为你让test 函数需要Cache,那么当你运行test() 时,你不会在这里注入Cache 对象:

    function test(Cache $cache)
    {
        dd($cache);
    }
    
    // here you need to pass instance of Cache
    test();
    

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

    test(new Cache);
    

    如果Cache 对象使用所有静态方法或类常量,则无需将其创建为可注入的,只需在Cache::class 引用的脚本中需要它的地方使用它;

    最后一种可能性是$cache 在其中一个文件中的某个include 中可用,尽管我在任何地方都看不到,但如果可用,您可以将test() 设为变量函数use():

    $test = function() use ($cache)
    {
        dd($cache);
    };
    
    // No injection needed
    $test();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2023-02-24
      • 2018-07-05
      相关资源
      最近更新 更多