2015-07-03 62 views
1

我正在嘗試引入一些Illuminate組件來拯救傳統應用程序,即容器,事件和路由器。嘗試將具體類綁定到接口時,我無法通過BindingResolutionException。Laravel外部的照明/容器自動綁定分辨率

的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來完成此項任務?如果是這樣,那是唯一的方法嗎?

預先感謝

回答

2

我意識到我實例化多個容器,而不是通過我曾首次創建一個(通過查看對象ID)。我的解決方案是將容器傳遞給路由器時,例如:

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

然後一切按預期工作。