使用PHP-DI将参数注入构造函数


Injecting parameters into constructor with PHP-DI

我正在努力让依赖项注入以我期望的方式工作-

我正在尝试注入一个类Api,它需要知道为特定用户连接到哪个服务器。这意味着在配置文件中重写构造函数属性是无用的,因为每个用户可能需要连接到不同的服务器。

class MyController {
    private $api;
    public function __construct(Api $api) {
        $this->api = $api;
    }
}
class Api {
     private $userServerIp;
     public function __construct($serverip) {
         $this->userServerIp = $serverip;
     }
}

如何为这个类注入正确的参数?有可能以某种方式推翻这个定义吗?是否有某种方法可以通过调用带有参数的容器来获取类?

为了(希望)澄清——我试图调用容器来实例化一个对象,同时将定义中的参数传递给它。

由于IP取决于用户,您可能有一些逻辑来执行user=>serverIP映射。它可能是从数据库中读取,或者是简单的基于id的分片,或者其他什么。使用该逻辑,您可以构建为特定用户创建ApiApiFactory服务:

class ApiFactory {
    private function getIp(User $user) {
        // simple sharding between 2 servers based on user id
        // in a real app this logic is probably more complex - so you will extract it into a separate class
        $ips = ['api1.example.com', 'api2.example.com'];
        $i = $user->id % 2;
        return $ips[$i];
    }
    public function createForUser(User $user) {
        return new Api($this->getIp($user);
    }
}

现在,您可以注入ApiFactory(假设您的控制器知道需要Api实例的用户),而不是将Api注入控制器

class MyController {
    private $apiFactory;
    public function __construct(ApiFactory $apiFactory) {
        $this->apiFactory = $apiFactory;
    }
    public function someAction() {
        $currentUser = ... // somehow get the user - might be provided by your framework, or might be injected as well
        $api = $this->apiFactory->createForUser($currentUser);
        $api->makeSomeCall();
    }
}

我不确定我是否完全理解您的问题,但您可以这样配置Api类:

return [
    'Foo' => function () {
        return new Api('127.0.0.1');
    },
];

查看文档以了解更多示例或详细信息:http://php-di.org/doc/php-definitions.html


编辑:

return [
    'foo1' => function () {
        return new Api('127.0.0.1');
    },
    'foo2' => function () {
        return new Api('127.0.0.2');
    },
];