通过app-> make()将变量传递给构造函数

时间:2018-03-19 14:39:12

标签: php laravel laravel-5

我有一个回购和一个eloquentrepo,请参阅代码。现在我想通过app->make()

将var传递给构造函数

这可能吗?我怎样才能做到这一点?

AppServiceProvoder:

app()->bind(TestRepository::class, EloquentTestRepository::class);

Appmake:

app()->(TestRepository::class)->getItem(TestModel::TEST_ITEM);

class EloquentTestRepository implements TestRepository {
    __construct($var){
        // do something with the $var
    }
}

尝试:

app()->(TestRepository::class,['test'])->getItem(TestModel::TEST_ITEM);

public function __construct(  $test)
{
    echo $test;
}

Error:

Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> $test ]] 

解决方案: 在AppServiceProvider中:

    app()->bind(FrequentieRepository::class,
        function($test){
            return new EloquentTestRepository($test);
        });

1 个答案:

答案 0 :(得分:0)

第二个参数可以是一个参数数组,请检查它here

<强>照亮/粉底/应用

/**
 * Resolve the given type from the container.
 *
 * (Overriding Container::make)
 *
 * @param  string  $abstract
 * @param  array  $parameters
 * @return mixed
 */
public function make($abstract, array $parameters = [])
{
    $abstract = $this->getAlias($abstract);
    if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
        $this->loadDeferredProvider($abstract);
    }
    return parent::make($abstract, $parameters);
}