【问题标题】:Dependency Injection via setter method通过 setter 方法进行依赖注入
【发布时间】:2019-10-18 12:17:07
【问题描述】:

在 PHP 中遇到依赖注入问题,我似乎无法找到答案。好的,快速 PHP 类:

<?php

namespace myapp;

use myapp\template;
use myapp\order;

class user {

    private $template;

    public function __construct(template $template) { 
         $this->template = $template;
     }

    public function add_order(order $order) { 
         // do something with $order here
    }

}

我正在使用来自http://php-di.org/ 的 php-di 包,尽管我愿意更改。我的问题是,如何直接注入到 add_order() 函数中?构造注入很简单,例如:

$container = new Di\Container();
$container->make(mapp\user);

我希望发生相同类型的注入,但同时直接调用 add_order() 函数。我想要这样的东西:

$container = new Di\Container();
$container->make(myapp\user::add_order);

有什么帮助吗?谢谢~

【问题讨论】:

    标签: php dependencies containers code-injection php-di


    【解决方案1】:

    你可以使用:

    return [
        'mapp\user' => DI\autowire()
            ->method('add_order', <put here what you want to inject>),
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多