4

In my App\Providers\RouteServiceProvider I did create the method register:

public function register()
{
    $this->app->bindShared('JustTesting', function($app)
    {
        die('got here!');
        // return new MyClass;
    });
}

Where should I use that? I did create a method in App\Http\Controllers\HomeController:

/**
 * ReflectionException in RouteDependencyResolverTrait.php line 53:
 * Class JustTesting does not exist
 *
 * @Get("/test")
 */
public function test(\JustTesting $test) {
    echo 'Hello';
}

But didn't works, I also can't use $this->app->make('JustTesting');

It works if I do as the code below, but I would like to Inject into controller.

/**
 * "got here!"
 *
 * @Get("/test")
 */
public function test() {
    \App::make('JustTesting');
}

How should I bind like I want to? And if it's not allowed, why should I use the bindShared method?

Samuel De Backer
  • 3,404
  • 2
  • 26
  • 37
Giovanne Afonso
  • 666
  • 7
  • 21

1 Answers1

1

It appears as though your first controller route is throwing a ReflectionException because the object JustTesting does not actually exist at the time the IoC Container is attempting to resolve it.

Also, you should code to an interface. Binding JustTestingInterace to MyClass would be so that Laravel knows "Ok, when an implementation of JustTestingInterface is requested, I should resolve it to MyClass."

RouteServiceProvider.php:

public function register()
{
    $this->app->bindShared('App\Namespace\JustTestingInterface', 'App\Namespace\MyClass');
}

Inside of your controller:

use Illuminate\Routing\Controller;
use App\Namespace\JustTestingInterface;

class TestController extends Controller {

    public function test(JustTestingInterface $test)
    {
        // This should work
        dd($test);
    }
}
Inda5th
  • 111
  • 5
  • I do not want to use `MyClass` because it can change to another class in future (e.g. another vendor, but implementing the same interface). So could I use `... test(JustTestingInterface $test)` in my controller? Then it should be resolved to `MyClass` (or another class that I want to bind with `bindShared` method) – Giovanne Afonso Nov 10 '14 at 14:50
  • @GiovanneAfonso I fixed my original code which was incorrect.... `JustTestingInterface` should be an interface that is implemented by `MyClass`. Then you would bind `JustTestingInterface` to `MyClass` so that Laravel will know to use `MyClass` when an implementation of `JustTestingInterface` is requested. – Inda5th Nov 10 '14 at 18:01