ServiceProvider在laravel 5.1中使用构造参数注册服务

时间:2015-06-12 04:11:49

标签: php laravel laravel-5

我使用的是laravel 5.1,我遇到了这个问题。

在我的AppServiceProvider.php注册方法

$this->app->singleton('PingppServices', function ($app, $params) {
    return new \App\Services\PingppServices($params['sid']);
});

在PingppServices.php中

private $sid;

public function __construct($params)
{
    $this->sid = $params['sid'];
}

public function foo()
{
    echo $this->sid;
}
控制器中的

我用它来称呼它

$pingppServices = app('PingppServices', ['sid' => 1]);
$pingppServices->foo();

所以我的问题是,在laravel 5.0中,我可以这样做app('PingppServices', 1);,在5.1中,第二个参数必须是一个数组。我看到app()方法没有变化,所以有什么变化?

这是使用构造参数解析服务的正确方法吗?

感谢。

2 个答案:

答案 0 :(得分:0)

很难说,没有洞察课程的目的和对整个代码的概述。

一般来说,我传递给类的构造函数的东西主要是依赖项和配置变量。与运行时数据相关的任何内容都应该具有单独的setter,或者应该作为参数传递给需要的方法。

就像我很难过,如果没有更多的洞察力,很难说。

示例:

photo = client.file({
  :body => IO.read("test/parsers.jpg"),
  :local_filename => "parsers.jpg",
  :content_type => "image/jpeg"
})

答案 1 :(得分:0)

与你说的不一样,在Laravel 5.1中,app()方法是

/**
 * Get the available container instance.
 *
 * @param  string  $make
 * @param  array   $parameters
 * @return mixed|\Illuminate\Foundation\Application
 */
function app($make = null, $parameters = [])
{
    if (is_null($make)) {
        return Container::getInstance();
    }

    return Container::getInstance()->make($make, $parameters);
}

最后,它将调用函数build($concrete, array $parameters = [])

所以,第二个参数必须是一个数组。