0

所以在試圖實現的IoC,DI,等在Laravel 4,我碰了壁。無論是我誤解的東西或做一些可怕的錯誤,不知道哪個...國際奧委會和接口綁定掛鉤22

所以我有一個類Person(「商務艙」,而不是一個模型或庫):

namespace Entities; 
use Interfaces\Person as PersonInterface; 
class Person implements PersonInterface {...} 

工廠其具有:

use Interfaces\Person; 
... 
App::singleton('user', function($app) { 
     ... 
     $user_object = new Person(); 
     ... 
}); 

和別名陣列中:

'Interfaces\Person' => 'Entities\Person' 

問題是,不工作,因爲Person類無法實現它的接口,因爲接口綁定回Person類:

Entities\Person cannot implement Entities\Person - it is not an interface 

我似乎在應用程序防止類使用的IoC和接口趕上22日被抓實際實例化。

不知道,如果是相關的,但把

App::bind('Interfaces\Person','Entities\Person'); 

在routes.php文件的文件似乎並沒有做任何事情(但是把它的別名數組中一樣)。當然,我在這裏做錯了事。有任何想法嗎?

回答

2

也許我可以提供幫助。要將接口綁定到IoC,您需要有接口和接口的實現。看起來你有這個步驟是正確的。你也想創建一個服務提供者。在這裏更多信息:http://laravel.com/docs/ioc#service-providers

刪除您從routes.php文件文件有任何綁定。服務提供者是綁定路由的東西,config/app.php將它註冊到IoC中,如下面更全面的描述。

服務提供商可能會是這個樣子:

文件名:ServiceProviders/PersonServiceProvider.php

<?php namespace ServiceProviders; 

use Illuminate\Support\ServiceProvider; 
use Entities\Person; 

class PersonServiceProvider extends ServiceProvider { 

/** 
* Register the binding. 
* 
* @return void 
*/ 
public function register() 
{ 
    $this->app->bind('Interfaces\Person', function() 
    { 
     return new Person(); 
    }); 
} 
} 

一旦服務提供商創建,在config/app.php文件進行註冊如下:

'ServiceProviders \ PersonServiceProvider',

不要使用別名。這用於註冊外牆的別名,如果我正確理解你的問題,這不是你在這裏試圖做的。

最後,遵循公認的Laravel的命名規則,我建議命名接口文件「PersonInterface.php」及其接口「界面PersonInterface。」同樣,實現文件可能被稱爲「EloquentPerson.php」和「類EloquentPerson擴展PersonInterface」。這假設你正在使用雄辯。它與你所擁有的相似,但我認爲類和接口名稱可以通過這些小小的調整使它更具可讀性。

+0

服務商!這就是我所錯過的。現在一切正常。非常感謝。好的接口命名建議;我有太多名爲「Person.php」的文件,並將該名稱空間別名爲「PersonInterface」... – Osan