0

I have an interface

interface RecordsService {
  public function getRecords();
}

and two implementations:

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


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

Now, in my controller I do DI like this:

class RecordsController {
  private $recordsService;

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

And I bind it like this:

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

Now, my question is, is it possible to implement this more dynamically, based on configuration, something like this:

switch( Config::get('config.records_source') ){
   case 'db':
     App::bind('RecordsService', 'DbRecordsService');
     break;
   case 'api':
     App::bind('RecordsService', 'ApiRecordsService');
     break; 
} 

and more important, is this a good practice ?

1 Answer 1

1

You can use for that an annonymous function like that:

App::bind('RecordsService', function() {
    switch( Config::get('config.records_source') ){
        case 'db':
            return new DbRecordsService;
        case 'api':
            return new ApiRecordsService;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.