php - Laravel 5.0 - 在哪里使用服务提供商的绑定(bind)?

标签 php laravel laravel-routing laravel-5

在我的 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/

相关文章:

php - RUBY 和 RAILS 相对于 PHP 和 CODEIGNITER 的主要优势是什么

php - SQL:GROUP BY 记录,然后从每个组中获取最后一条记录?

laravel - 如何获取使用 Laravel 中的存储外观访问的 AWS S3 中图像的尺寸?

mysql - 如何通过多标签选择产品

php - Laravel redirect::route 在页面加载之间显示一条消息

php - 如何使 Laravel 中的路由不区分大小写?

php - %cd 在 ajax 到 php 调用中转换为 Í

php - 大量空格进入数据库......(PHP,Mysql)

mysql - 无法添加外键约束 [Laravel 5.6]

php - Laravel 5 本地化 : exclude/public/directory