Reputation: 1627
I have been refactoring code to learn about services, DI, etc.
This is part of my Controller
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()
));
}
Now I'd like to make this code thinner, but after trying different formulas I haven't been able to:
1.- put the configuration parameters $weatherConfig in a: container
? (is this a good solution?)
2.- Make the render line thinner
3.- Are these good ideas thinking that maybe I'd like to add more cities (configuration settings) in the future. Suggestions?
Cheers.-
Upvotes: 0
Views: 91
Reputation: 5133
Overall, the code is ok but I can give some advices:
_
to identify your own services. Instead, prefix it with your bundle id: wea_ther
(this is Symfony2's recommandation)._weather_service
. I would prefer something like wea_ther.weather_forecaster
. Same remark for the class location and name.geo.location
in the configuration of your bundle. At least prefix it with your bundle id.Here is the corresponding code:
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%]
Upvotes: 1
Reputation: 1627
I solved the issue this way, I'd appreciate if someone can tell me about the correctness of the code. I still need to meditate on what I did :P
Controller:
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%]
Upvotes: 0