【问题标题】:Automatic Binding Resolution with Illuminate/Container outside of Laravel在 Laravel 之外使用 Illuminate/Container 自动绑定分辨率
【发布时间】:2015-09-21 18:29:03
【问题描述】:

我正在尝试引入一些 Illuminate 组件来挽救遗留应用程序,即容器、事件和路由器。尝试将具体类绑定到接口时,我无法通过 BindingResolutionException。

index.php

<?php

require __DIR__ . '/vendor/autoload.php';

$app = new Illuminate\Container\Container;

$app->bind('dispatcher', function () {
    return new Illuminate\Events\Dispatcher;
});

$app->bind('router', function ($app) {
    return new Illuminate\Routing\Router($app['dispatcher']);
});

// This is the interface I'm trying to bind
$app->bind('App\Logable', function () {
    return new App\Logger();
});

$router = $app['router'];

// This is where I'm trying to use automatic binding resolution
$router->get('/', function (App\Logable $logger) {
    return $logger->log();
});

$request = Illuminate\Http\Request::createFromGlobals();
$response = $router->dispatch($request);
$response->send();

src/Logable.php

<?php

namespace App;

interface Logable
{
    public function log();
}

src/Logger.php

<?php

namespace App;

class Logger implements Logable
{
    public function log()
    {
        var_dump($this);
    }
}

有人有什么想法吗?我不确定是否需要注册为服务提供商,或者是否需要为此使用 Illuminate\Application\Foundation?如果是这样,那是唯一的方法吗?

提前致谢

【问题讨论】:

    标签: php laravel ioc-container


    【解决方案1】:

    我意识到我正在实例化多个容器,而不是传递我第一次创建的容器(通过查看对象 ID)。我的解决方案是在实例化时将容器传递给路由器:

    $app->bind('router', function ($app) {
        return new Illuminate\Routing\Router($app['dispatcher'], $app);
    });
    

    然后一切都按预期进行。

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多