4

在我的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');

如果我按照下面的代码进行操作,它可以工作,但我想注入控制器。

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

我应该如何像我想要的那样绑定?如果不允许,我为什么要使用该bindShared方法?

4

1 回答 1

1

看起来好像您的第一个控制器路由正在引发 ReflectionException,因为JustTesting在 IoC 容器尝试解析它时该对象实际上并不存在。

此外,您应该对接口进行编码。绑定JustTestingInteraceMyClass将使 Laravel 知道“好的,当JustTestingInterface请求实现时,我应该将其解析为MyClass.”。

RouteServiceProvider.php:

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

在您的控制器内部:

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

class TestController extends Controller {

    public function test(JustTestingInterface $test)
    {
        // This should work
        dd($test);
    }
}
于 2014-11-09T16:21:00.680 回答