Laravel 4 - 基于配置的依赖注入?

时间:2016-05-04 12:33:40

标签: laravel laravel-4

我有一个界面

$items = explode(',', $res["file"]);

和两个实现:

interface RecordsService {
  public function getRecords();
}

现在,在我的控制器中,我这样做DI:

public class ApiRecordsService implements RecordsService {
  public function getRecords() {
   //get records from api
  }
}


public class DbRecordsService implements RecordsService {
  public function getRecords() {
   //get records from db
  }
}

我这样绑定它:

class RecordsController {
  private $recordsService;

  public function __construct(RecordsService $recordsService) {
    $this->recordsService= $recordsService;
  }
}

现在,我的问题是,是否可以根据配置更加动态地实现这一点,如下所示:

App::bind('RecordsService', 'ApiRecordsService');

更重要的是,这是一个好习惯吗?

1 个答案:

答案 0 :(得分:1)

您可以使用这样的匿名函数:

App::bind('RecordsService', function() {
    switch( Config::get('config.records_source') ){
        case 'db':
            return new DbRecordsService;
        case 'api':
            return new ApiRecordsService;
    }
});
相关问题