Answer the question
In order to leave comments, you need to log in
Laravel5: How to inject a dependency in which a constructor with its own parameters?
Working with layered architecture, using DI and so on. I ran into the following problem:
For example, there is such a controller code that has an index action that injects MyService into itself.
For simplicity and brevity, interfaces are not considered.
<?php
namespace App\Http\Controllers;
use App\Http\Requests\TestRequest;
use App\Services\MyService;
class TestController extends Controller
{
protected $myService;
public function index(TestRequest $request, MyService $myService)
{
echo $request->get('var1');
}
}
<?php
namespace App\Services;
class MyService
{
private $data = true;
public function __construct($data)
{
$this->data = (bool)$data;
}
public function getData()
{
return $this->data;
}
}
BindingResolutionException in Container.php line 849: Unresolvable dependency resolving [Parameter #0 [ <required> $data ]] in class App\Services\MyService
Answer the question
In order to leave comments, you need to log in
The $data variable must have a class or interface definition, otherwise Laravel does not even know what to substitute in $data.
<?php
namespace App\Services;
use SomeInterface;
class MyService
{
private $data = true;
public function __construct(SomeInterface $data)
{
$this->data = (bool)$data;
}
public function getData()
{
return $this->data;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question