问题是我不知道如何绑定一个接口的多个实现.
例:
// One interface interface SmsInterface { ... } // First implementation using SmsCoin class SmscoinAPI implements SmsInterface { ... } // Second implementation using Fortumo class FortumoAPI implements SmsInterface { ... }
//两个控制器:
class SmsCoinController { public function __construct(SmsInterface $sms) { $this->sms = $sms } } class FortumoController { public function __construct(SmsInterface $sms) { $this->sms = $sms } }
问题:我如何使用FortumoController实现FortumoApi绑定SmsInterface,并将SmsInterface绑定到SmsCoinController的实现SmsCoinApi?
我使用ServiceProvider来注册绑定,我可以在那里做吗?如果没有绑定的位置?
编辑:
我无法在任何地方得到答案,阅读许多laravel书籍,据说在任何地方使用多个实现,但没有显示如何交换/切换这些实现.
如果我有一个接口和两个实现,如何在控制器中绑定和交换它们.我是否需要在该控制器构造函数方法中执行此操作?或通过检查控制器的路线或在filters.php的路线?还是在服务提供商?以及如何在技术上相关地编写该代码?
这个问题花了我很长时间来解决它.在Laravel 5.0出局后,我发布了使用Contextual绑定找到的解决方案
考虑这个例子,当一个控制器需要一个具有多个实现的接口时.
<?php // We are creating one abstract controller with one logic abstract class AbstractSearchController { protected $searchService; public function __construct(SearchServiceInterface $searchService) { $this->searchService = $searchService; } public function getResult($keyword) { return $this->searchService->getItems($keyword); } } // In routes.php file we can point url like: http://example.com/search/posts/?keyword=my-search-keyword to use // something like this: Route::resource('search/posts', 'PostSearchController', ['only' => ['index']]); class PostSearchController extends AbstractSearchController { // No code here as this controller only is needed so that we can point Specific implementation to it } // In routes.php file we can point url like: http://example.com/search/members/?keyword=my-search-keyword to use // something like this: Route::resource('search/members', 'MemberSearchController', ['only' => ['index']]); class MemberSearchController extends AbstractSearchController { // } // Our main interface that will have multiple implementations at same time interface SearchServiceInterface { public function getItems($keyword); } // Our first implementation of interface class MemberSearchRepo implements SearchServiceInterface { public function getItems($keyword) { // Get members by keyword } } // Our second implementation of interface class PostSearchRepo implements SearchServiceInterface { public function getItems($keyword) { // Get posts by keyword } } // When PostsSearchController needs Search Logic point IoC to give our first implementation $this->app->when('PostSearchController')->needs('SearchServiceInterface')->give('PostSearchRepo'); // When MemberSearchController needs Search Logic point IoC to give our seconds implementation $this->app->when('MemberSearchController')->needs('SearchServiceInterface')->give('MemberSearchRepo');
我希望这个扩展的例子可以帮助人们理解如何实现Laravel 4.x所需的功能以及Laravel 5提供的功能