【问题标题】:Laravel 5.0 - Where to use bindings from Service Providers?Laravel 5.0 - 在哪里使用服务提供者的绑定?
【发布时间】:2014-12-25 07:19:54
【问题描述】:

在我的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 方法?

【问题讨论】:

    标签: php laravel laravel-routing laravel-5


    【解决方案1】:

    您的第一个控制器路由似乎抛出了 ReflectionException,因为在 IoC 容器尝试解析它时对象 JustTesting 实际上并不存在。

    此外,您应该对接口进行编码。将 JustTestingInterace 绑定到 MyClass 将使 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);
        }
    }
    

    【讨论】:

    • 我不想使用MyClass,因为它将来可能会更改为另一个类(例如,另一个供应商,但实现相同的接口)。那么我可以在我的控制器中使用... test(JustTestingInterface $test) 吗?然后它应该被解析为MyClass(或者我想用bindShared方法绑定的另一个类)
    • @GiovanneAfonso 我修复了不正确的原始代码....JustTestingInterface 应该是由MyClass 实现的接口。然后你将 JustTestingInterface 绑定到 MyClass 以便 Laravel 在请求 JustTestingInterface 的实现时知道使用 MyClass
    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2016-08-05
    • 2018-12-03
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多