ServiceProvider register services with construct parameters in laravel 5.1
I am using laravel 5.1 and I am having these problems.
in my AppServiceProvider.php register method
$this->app->singleton('PingppServices', function ($app, $params) {
return new \App\Services\PingppServices($params['sid']);
});
at PingppServices.php
private $sid;
public function __construct($params)
{
$this->sid = $params['sid'];
}
public function foo()
{
echo $this->sid;
}
in the controller i use this to call it
$pingppServices = app('PingppServices', ['sid' => 1]);
$pingppServices->foo();
So my question is: in laravel 5.0 I can do it like app('PingppServices', 1);
, in 5.1 the second argument should be an array. I see that the app () method has no change, so what's the change?
And is this the correct way to resolve services with design parameters?
thank.
source to share
It's hard to tell without having an understanding of the purpose of the class and an overview of the entire code.
In general, whatever you pass to a class constructor is mostly dependencies and configuration variables. Anything related to data at runtime must have a separate delimiter, or must be passed as an argument to a method where appropriate.
How sad I am, it's really hard to tell without a deeper understanding.
Example:
class Foobar {
private $pingppService;
public function __construct(PingppServices $pingppService) {
$this->pingppService = $pingppService;
}
public function wtf() {
$this->pingppService->setParams(Request::all());
$this->pingppService->foo();
}
}
source to share
Not like you said in Laravel 5.1 the app () method
/**
* 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);
}
Finally, it will call the function build($concrete, array $parameters = [])
.
So the second argument should be an array.
source to share