如何使用Laravel的容器将“动态”属性传递给注入的类?

时间:2019-06-27 02:03:32

标签: php laravel dependency-injection containers

我有一个要插入另一个类的类(例如,一个控制器)。此类将模型作为第一个参数,并将Guzzle HTTP客户端对象作为第二个参数。

<?php
namespace App\Services;

use App\MyModel;
use GuzzleHttp\Client;

class MyClass
{
    private $model;
    private $client;

    public function __construct(MyModel $model, Client $client)
    {
        $this->model = $model;
        $this->client = $client;
    }
}

MyModel具有Guzzle客户端将用于其默认配置(传递给其构造函数)的URL。

如果没有DI,它将看起来像这样。

public function myControllerMethod()
{
    $model = new MyModel;
    $client = new Client([
        'base_uri' => $model->url, 
        'headers' => [
            'Authorization' => "Bearer {$model->api_token}",
         ]
    ]);

    $my_class = new MyClass($model, $client);
}

我将如何进行重构,这样我就可以将MyClass注入控制器方法而无需基于给定模型手动设置$ client了?这有可能吗?

public function myControllerMethod(MyModel $model, MyClass $my_class)
{
    // The model could come from the request or injected into this method (as shown).

    $my_class->doSomething();
}

0 个答案:

没有答案