我试图通过使用Laravel服务提供商来学习IoC的概念。到目前为止我所读到的内容,您应该包含依赖于服务提供者中其他类的所有类创建逻辑。公平和正方形,但我想确保我以正确的方式做到这一点。
我的应用程序将使用抽象Tracker
类的子类,根据您向服务提供者提供的常量,它应该加载不同的类。这是正确的方法吗?
服务提供商:
class TrackerServiceProvider extends \Illuminate\Support\ServiceProvider {
const TRACKER_API = 0;
const TRACKER_SITE = 1;
public function register() {
$this->app->bind('Tracker', function($app, $parameters) {
switch($parameters['method']) {
case static::TRACKER_API:
return new TrackerAPI(new cURL(), new Shipment($parameters['number']));
break;
case static::TRACKER_SITE:
return new TrackerSite(new cURL(), new Shipment($parameters['number']));
break;
default:
throw Exception('Unknown tracker method provided.');
break;
}
});
}
}
抽象的Tracker类(只是基础):
abstract class Tracker {
protected $curl;
protected $shipment;
function __construct(cURL $curl, Shipment $shipment) {
$this->curl = $curl;
$this->shipment = $shipment;
}
}
或者我应该在register
方法中创建两个不同的绑定,每个类一个?像这样:
class TrackerServiceProvider extends \Illuminate\Support\ServiceProvider {
public function register() {
$this->app->bind('TrackerAPI', function($app, $number) {
return new TrackerAPI(new cURL(), new Shipment($number));
});
$this->app->bind('TrackerSite', function($app, $parameters) {
return new TrackerSite(new cURL(), new Shipment($number));
});
}
}
答案 0 :(得分:1)
我更喜欢在此处设置Factory
以将其与ServiceProvider
分离。以下代码只是一个演示,最好不要使用下面TrackerFactory
中的静态方法。
class TrackerFactory {
const TRACKER_API = 0;
const TRACKER_SITE = 1;
public static function make($parameters) {
switch($parameters['method']) {
case static::TRACKER_API:
return new TrackerAPI(new cURL(), new Shipment($parameters['number']));
break;
case static::TRACKER_SITE:
return new TrackerSite(new cURL(), new Shipment($parameters['number']));
break;
default:
throw Exception('Unknown tracker method provided.');
break;
}
}
}
然后绑定它。
class TrackerServiceProvider extends \Illuminate\Support\ServiceProvider {
public function register() {
$this->app->bind('Tracker', function($app, $parameters) {
return TrackerFactory::make($parameters)
});
}
}