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?

1 Answer 1

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);
    }
}
2
  • 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) Nov 10, 2014 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, 2014 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.