在我的 App\Providers\RouteServiceProvider
中,我确实创建了方法 register
:
public function register()
{
$this->app->bindShared('JustTesting', function($app)
{
die('got here!');
// return new MyClass;
});
}
我应该在哪里使用它?我确实在 App\Http\Controllers\HomeController
中创建了一个方法:
/**
* ReflectionException in RouteDependencyResolverTrait.php line 53:
* Class JustTesting does not exist
*
* @Get("/test")
*/
public function test(\JustTesting $test) {
echo 'Hello';
}
但是没用,我也不能用 $this->app->make('JustTesting');
如果我按照下面的代码进行操作,它会起作用,但我想注入(inject) Controller 。
/**
* "got here!"
*
* @Get("/test")
*/
public function test() {
\App::make('JustTesting');
}
我应该如何绑定(bind)?如果不允许,我为什么要使用 bindShared
方法?
最佳答案
看起来您的第一个 Controller 路由正在抛出 ReflectionException,因为对象 JustTesting
在 IoC 容器尝试解析它时实际上并不存在。
此外,您应该针对接口(interface)进行编码。将 JustTestingInterace
绑定(bind)到 MyClass
将使 Laravel 知道“好的,当请求 JustTestingInterface
的实现时,我应该将其解析为 我的类(class)
。”
RouteServiceProvider.php:
public function register()
{
$this->app->bindShared('App\Namespace\JustTestingInterface', 'App\Namespace\MyClass');
}
Controller 内部:
use Illuminate\Routing\Controller;
use App\Namespace\JustTestingInterface;
class TestController extends Controller {
public function test(JustTestingInterface $test)
{
// This should work
dd($test);
}
}
关于php - Laravel 5.0 - 在哪里使用服务提供商的绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632860/