Romano Schoonheim
Romano Schoonheim

Reputation: 101

Laravel 5.7 Service Container | DI / Passing parameters to a method in a controller

I'm experiencing difficulties to find a elegant solution to inject parameters into controller methods. I want to move my factories into the service container because the code more complicated for inexperienced programmers. I tried to inject parameters into a controller function using the bindMethod of the service container but i didn't succeed yet.

Does someone know how to accomplish this?

Code I tried to inject parameters into controller methods

Laravel AppServiceProvider

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $container = app();
        $container->bindMethod('TestController@index', function ($controller, $container) {
            return $controller->index('TestData');
        });
    }
}

Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
    public function index($test)
    {
        // do something with the implementations.
    }
}

Example of what I want to achieve

The current situation (simplified).

public function index()
{
    $car = CarFactory::get();
    $food = FoodFactory::get();
}

I want it to look like this:

public function index($car, $food)
{
    // do something with the implementations.
}

thanks in advance!

Upvotes: 1

Views: 812

Answers (2)

Romano Schoonheim
Romano Schoonheim

Reputation: 101

It is possible to use a factory to inject a implementation of a specific interface with the service container. You could do that with the bind method.

<?php

namespace App\Providers;

use App\ExampleImplementation;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'App\IExample',
            function() {
                return (new factory())->make();
            }
        );
    }
}

I'm researching of this is a practical approach to remove factories from controllers.

Thanks guys!

Upvotes: 1

Jeff
Jeff

Reputation: 25221

You can do it in the constructor:

private $carFactory;

public function __construct(CarFactory $carFactory){
  $this->carFactory = $carFactory;
}

Then access it anytime with $this->carFactory

Upvotes: 0

Related Questions