Reputation: 706
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?
Upvotes: 4
Views: 3976
Reputation: 121
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);
}
}
Upvotes: 1