【问题标题】:IoC and interface binding catch 22IoC 和接口绑定 catch 22
【发布时间】:2013-10-25 03:37:33
【问题描述】:

所以在尝试在 Laravel 4 中实现 IoC、DI 等时,我碰壁了。要么是我误解了什么,要么是做错了什么,不知道是哪一个......

所以我有一个类 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 文件中似乎没有做任何事情(但把它放在 aliases 数组中)。我肯定在这里做错了什么。有什么想法吗?

【问题讨论】:

    标签: php interface dependency-injection inversion-of-control laravel-4


    【解决方案1】:

    也许我可以帮忙。要将接口绑定到 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”,并将其接口命名为“interface PersonInterface”。类似地,实现文件可能被称为“EloquentPerson.php”和“类 EloquentPerson extends PersonInterface”。这假设您使用的是 Eloquent。它与您所拥有的类似,但我认为类和接口名称可以通过这些小调整使其更具可读性。

    【讨论】:

    • 服务提供商!这就是我所缺少的。现在一切正常。非常感谢。接口命名的好建议;我有太多名为“Person.php”的文件,并且无论如何都将该命名空间别名为“PersonInterface”......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多