因此,在试图在Laravel 4中实现IoC、DI等时,我遇到了麻烦。要么我误解了什么,要么做了可怕的错事,不知道是哪一个.
因此,我有一个类人(“商务舱”,而不是模型或图书馆):
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文件中,似乎什么都不做(但是把它放在别名数组中就可以了)。我肯定是在做错事。有什么想法吗?
发布于 2013-10-17 05:30:49
也许我能帮忙。要将接口绑定到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“。这假设你用的是雄辩。它与您所拥有的相似,但我认为类和接口名称可以通过这些小的调整使其更加可读性。
https://stackoverflow.com/questions/19413303
复制相似问题