N
N
nepster-web2016-09-30 11:47:36
Laravel
nepster-web, 2016-09-30 11:47:36

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');
    }

}

As we know, laravel5 itself automatically injects the requested classes from the DIC. Everything would be fine and great, but what if the service code looks like this:
<?php

namespace App\Services;

class MyService
{
    private $data = true;

    public function __construct($data)
    {
        $this->data = (bool)$data;
    }

    public function getData()
    {
        return $this->data;
    }
}

That is, setters are not needed there and the argument is expected explicitly in the constructor. Accordingly, in this scenario, we will see an error of approximately the following content:
BindingResolutionException in Container.php line 849: Unresolvable dependency resolving [Parameter #0 [ <required> $data ]] in class App\Services\MyService

Yes, we can bind default data through the interface and all that, but what if the data that we need in the MyService constructor is exactly the data that I expect to receive from the controller, i.e. $request->get('var1');
Based on this, please tell me how to solve this problem?
I'm looking towards factories, but I would like to get a recommendation and an example of use, thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nimfus, 2016-09-30
@Nimfus

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 question

Ask a Question

731 491 924 answers to any question