Services

Exclusive offer: get 50% off this eBook here
Extending Symfony2 Web Application Framework

Extending Symfony2 Web Application Framework — Save 50%

Optimize, audit, and customize web applications with Symfony with this book and ebook

$20.99    $10.50
by Sébastien Armand | March 2014 | Open Source Web Development

In this article by Sébastien Armand, the author of the book Extending Symfony2 Web Application Framework, has discussed about the basics of services in the Symfony2 framework. A service is an essential and core concept in Symfony2. In fact, most of the framework itself is just a big set of predefined services that are ready to use. As an example, if you just set up a new installation of Symfony2, from your project root, you can type php app/console container:debug to see the full list of services currently defined in your application. As you can see, even before we start writing anything for our application, we already have almost 200 services defined. The php app/console container:debug <service_name> command will provide information about a specific service and will be a useful command to refer to throughout the article.

(For more resources related to this topic, see here.)

Services

A service is just a specific instance of a given class. For example, whenever you access doctrine such as $this->get('doctrine'); in a controller, it implies that you are accessing a service. This service is an instance of the Doctrine EntityManager class, but you never have to create this instance yourself. The code needed to create this entity manager is actually not that simple since it requires a connection to the database, some other configurations, and so on. Without this service already being defined, you would have to create this instance in your own code. Maybe you will have to repeat this initialization in each controller, thus making your application messier and harder to maintain.

Some of the default services present in Symfony2 are as follows:

  • The annotation reader
  • Assetic—the asset management library
  • The event dispatcher
  • The form widgets and form factory
  • The Symfony2 Kernel and HttpKernel
  • Monolog—the logging library
  • The router
  • Twig—the templating engine

It is very easy to create new services because of the Symfony2 framework. If we have a controller that has started to become quite messy with long code, a good way to refactor it and make it simpler will be to move some of the code to services. We have described all these services starting with "the" and a singular noun. This is because most of the time, services will be singleton objects where a single instance is needed.

A geolocation service

In this example, we imagine an application for listing events, which we will call "meetups". The controller makes it so that we can first retrieve the current user's IP address, use it as basic information to retrieve the user's location, and only display meetups within 50 kms of distance to the user's current location. Currently, the code is all set up in the controller. As it is, the controller is not actually that long yet, it has a single method and the whole class is around 50 lines of code. However, when you start to add more code, to only list the type of meetups that are the user's favorites or the ones they attended the most. When you want to mix that information and have complex calculations as to which meetups might be the most relevant to this specific user, the code could easily grow out of control!

There are many ways to refactor this simple example. The geocoding logic can just be put in a separate method for now, and this will be a good step, but let's plan for the future and move some of the logic to the services where it belongs. Our current code is as follows:

use Geocoder\HttpAdapter\CurlHttpAdapter; use Geocoder\Geocoder; use Geocoder\Provider\FreeGeoIpProvider; public function indexAction()   {

Initialize our geocoding tools (based on the excellent geocoding library at http://geocoder-php.org/) using the following code:

$adapter = new CurlHttpAdapter(); $geocoder = new Geocoder(); $geocoder->registerProviders(array( new FreeGeoIpProvider($adapter), ));

Retrieve our user's IP address using the following code:

$ip = $this->get('request')->getClientIp(); // Or use a default one     if ($ip == '127.0.0.1') {   $ip = '114.247.144.250'; }

Get the coordinates and adapt them using the following code so that they are roughly a square of 50 kms on each side:

$result = $geocoder->geocode($ip); $lat = $result->getLatitude(); $long = $result->getLongitude(); $lat_max = $lat + 0.25; // (Roughly 25km) $lat_min = $lat - 0.25; $long_max = $long + 0.3; // (Roughly 25km) $long_min = $long - 0.3;

Create a query based on all this information using the following code:

$em = $this->getDoctrine()->getManager(); $qb = $em->createQueryBuilder(); $qb->select('e')     ->from('KhepinBookBundle:Meetup, 'e')     ->where('e.latitude < :lat_max')     ->andWhere('e.latitude > :lat_min')     ->andWhere('e.longitude < :long_max')     ->andWhere('e.longitude > :long_min')     ->setParameters([       'lat_max' => $lat_max,       'lat_min' => $lat_min,       'long_max' => $long_max,       'long_min' => $long_min     ]);

Retrieve the results and pass them to the template using the following code:

$meetups = $qb->getQuery()->execute(); return ['ip' => $ip, 'result' => $result, 'meetups' => $meetups]; }

The first thing we want to do is get rid of the geocoding initialization. It would be great to have all of this taken care of automatically and we would just access the geocoder with: $this->get('geocoder');.

You can define your services directly in the config.yml file of Symfony under the services key, as follows:

services:   geocoder:     class: Geocoder\Geocoder

That is it! We defined a service that can now be accessed in any of our controllers. Our code now looks as follows:

// Create the geocoding class $adapter = new \Geocoder\HttpAdapter\CurlHttpAdapter(); $geocoder = $this->get('geocoder'); $geocoder->registerProviders(array(     new \Geocoder\Provider\FreeGeoIpProvider($adapter), ));

Well, I can see you rolling your eyes, thinking that it is not really helping so far. That's because initializing the geocoder is a bit more complex than just using the new \Geocoder\Geocoder() code. It needs another class to be instantiated and then passed as a parameter to a method. The good news is that we can do all of this in our service definition by modifying it as follows:

services:     # Defines the adapter class     geocoder_adapter:         class: Geocoder\HttpAdapter\CurlHttpAdapter         public: false     # Defines the provider class     geocoder_provider:         class: Geocoder\Provider\FreeGeoIpProvider         public: false         # The provider class is passed the adapter as an argument         arguments: [@geocoder_adapter]     geocoder:         class: Geocoder\Geocoder         # We call a method on the geocoder after initialization to
set up the         # right parameters         calls:             - [registerProviders, [[@geocoder_provider]]]

It's a bit longer than this, but it is the code that we never have to write anywhere else ever again. A few things to notice are as follows:

  • We actually defined three services, as our geocoder requires two other classes to be instantiated.
  • We used @+service_name to pass a reference to a service as an argument to another service.
  • We can do more than just defining new Class($argument); we can also call a method on the class after it is instantiated. It is even possible to set properties directly when they are declared as public.
  • We marked the first two services as private. This means that they won't be accessible in our controllers. They can, however, be used by the Dependency Injection Container (DIC) to be injected into other services.

Our code now looks as follows:

// Retrieve current user's IP address $ip = $this->get('request')->getClientIp(); // Or use a default one if ($ip == '127.0.0.1') {     $ip = '114.247.144.250'; } // Find the user's coordinates $result = $this->get('geocoder')->geocode($ip); $lat = $result->getLatitude(); // ... Remaining code is unchanged

Here, our controllers are extending the BaseController class, which has access to DIC since it implements the ContainerAware interface. All calls to $this->get('service_name') are proxied to the container that constructs (if needed) and returns the service.

Let's go one step further and define our own class that will directly get the user's IP address and return an array of maximum and minimum longitude and latitudes. We will create the following class:

namespace Khepin\BookBundle\Geo; use Geocoder\Geocoder; use Symfony\Component\HttpFoundation\Request; class UserLocator {     protected $geocoder;     protected $user_ip;     public function__construct(Geocoder $geocoder, Request $request) {         $this->geocoder = $geocoder;         $this->user_ip = $request->getClientIp();         if ($this->user_ip == '127.0.0.1') {             $this->user_ip = '114.247.144.250';         }     }     public function getUserGeoBoundaries($precision = 0.3) {         // Find the user's coordinates         $result = $this->geocoder->geocode($this->user_ip);         $lat = $result->getLatitude();         $long = $result->getLongitude();         $lat_max = $lat + 0.25; // (Roughly 25km)         $lat_min = $lat - 0.25;         $long_max = $long + 0.3; // (Roughly 25km)         $long_min = $long - 0.3;         return ['lat_max' => $lat_max, 'lat_min' => $lat_min,            'long_max' => $long_max, 'long_min' => $long_min];     } }

It takes our geocoder and request variables as arguments, and then does all the heavy work we were doing in the controller at the beginning of the article. Just as we did before, we will define this class as a service, as follows, so that it becomes very easy to access from within the controllers:

# config.yml services:     #...     user_locator:        class: Khepin\BookBundle\Geo\UserLocator        scope: request        arguments: [@geocoder, @request]

Notice that we have defined the scope here. The DIC has two scopes by default: container and prototype, to which the framework also adds a third one named request. The following table shows their differences:

Scope

Differences

Container

All calls to $this->get('service_name') return the sameinstance of the service.

Prototype

Each call to $this->get('service_name') returns a new instance of the service.

Request

Each call to $this->get('service_name') returns the same instance of the service within a request. Symfony can have subrequests (such as including a controller in Twig).

Now, the advantage is that the service knows everything it needs by itself, but it also becomes unusable in contexts where there are no requests. If we wanted to create a command that gets all users' last-connected IP address and sends them a newsletter of the meetups around them on the weekend, this design would prevent us from using the Khepin\BookBundle\Geo\UserLocator class to do so.

As we see, by default, the services are in the container scope, which means they will only be instantiated once and then reused, therefore implementing the singleton pattern. It is also important to note that the DIC does not create all the services immediately, but only on demand. If your code in a different controller never tries to access the user_locator service, then that service and all the other ones it depends on (geocoder, geocoder_provider, and geocoder_adapter) will never be created.

Also, remember that the configuration from the config.yml is cached when on a production environment, so there is also little to no overhead in defining these services.

Our controller looks a lot simpler now and is as follows:

$boundaries = $this->get('user_locator')->getUserGeoBoundaries(); // Create our database query $em = $this->getDoctrine()->getManager(); $qb = $em->createQueryBuilder(); $qb->select('e')     ->from('KhepinBookBundle:Meetup', 'e')     ->where('e.latitude < :lat_max')     ->andWhere('e.latitude > :lat_min')     ->andWhere('e.longitude < :long_max')     ->andWhere('e.longitude > :long_min')     ->setParameters($boundaries); // Retrieve interesting meetups $meetups = $qb->getQuery()->execute(); return ['meetups' => $meetups];

The longest part here is the doctrine query, which we could easily put on the repository class to further simplify our controller.

As we just saw, defining and creating services in Symfony2 is fairly easy and inexpensive. We created our own UserLocator class, made it a service, and saw that it can depend on our other services such as @geocoder service. We are not finished with services or the DIC as they are the underlying part of almost everything related to extending Symfony2.

Summary

In this article, we saw the importance of services and also had a look at the geolocation service. We created a class, made it a service, and saw how it can depend on our other services.

Resources for Article:


Further resources on this subject:


Extending Symfony2 Web Application Framework Optimize, audit, and customize web applications with Symfony with this book and ebook
Published: March 2014
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

About the Author :


Sébastien Armand

Sébastien Armand is a software developer based in Beijing, China. He spent most of the past five years working with Symfony, building internal IT systems. He co-founded mashupsports.com, a social website for sports enthusiasts based on Symfony2. He contributed to Symfony and the Symfony documentation on many occasions.

Books From Packt


Symfony 1.3 Web Application Development
Symfony 1.3 Web Application Development

PHP 5 CMS Framework Development - 2nd Edition
PHP 5 CMS Framework Development - 2nd Edition

Persistence in PHP with Doctrine ORM
Persistence in PHP with Doctrine ORM

Instant PhpStorm Starter
Instant PhpStorm Starter

Learning FuelPHP for Effective PHP Development
Learning FuelPHP for Effective PHP Development

PHP 5 E-commerce Development
PHP 5 E-commerce Development

Laravel Application Development Blueprints
Laravel Application Development Blueprints

Mastering Web Application Development with AngularJS
Mastering Web Application Development with AngularJS


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software