我一直在重构学习有关服务,DI等的代码。
这是我的控制器
的一部分public function indexAction()
{
$weatherConfig = array(
'city' => 'Detroit',
'lang' => 'en',
'units' => 'metric'
);
$weather = new WeatherService($this->get('_weather_finder'), $weatherConfig);
return $this->render('WeaTherBundle:Weather:index.html.twig',
array(
'weather' => $weather->getWeather()
));
}
现在我想让这段代码变得更薄,但在尝试了不同的公式之后,我还没有能够:
1.-将配置参数 $ weatherConfig 放入:container
? (这是一个很好的解决方案吗?)
2.-使渲染线更薄
3.-这些好主意是否在考虑我未来可能会添加更多城市(配置设置)。建议?
干杯.-
答案 0 :(得分:1)
总的来说,代码还可以,但我可以给出一些建议:
_
来标识自己的服务。相反,请在其前面添加您的包ID:wea_ther
(这是Symfony2的推荐)。_weather_service
。我更喜欢像wea_ther.weather_forecaster
这样的东西。类位置和名称也一样。geo.location
放在configuration of your bundle中。至少在它前面附上你的包ID。以下是相应的代码:
parameters:
wea_ther.weather_finder.class: Cmfcmf\OpenWeatherMap
wea_ther.weather_forecaster.class: Wea\TherBundle\Weather\Forecaster
wea_ther.geo_location:
city: Santiago de Chile
lang: en
units: metric
services:
wea_ther.weather_finder:
class: "%wea_ther.weather_finder.class%"
wea_ther.weather_forecaster:
class: '%wea_ther.weather_forecaster.class%'
arguments: [@wea_ther.weather_finder, %wea_ther.geo_location%]
答案 1 :(得分:0)
我以这种方式解决了这个问题,如果有人能告诉我代码的正确性,我会很感激。我仍然需要默想我的所作所为:P
<强>控制器强>:
public function indexAction()
{
$weather = $this->get('_weather_service');
return $this->render('WeaTherBundle:Weather:index.html.twig',
array(
'weather' => $weather->getWeather()
));
}
<强> services.yml 强>:
parameters:
_weather_finder.class: Cmfcmf\OpenWeatherMap
_weather_service.class: Wea\TherBundle\Services\WeatherService
geo.location:
city: Santiago de Chile
lang: en
units: metric
services:
_weather_finder:
class: "%_weather_finder.class%"
_weather_service:
class: '%_weather_service.class%'
arguments: [@_weather_finder, %geo.location%]