Symfony Services Cookbook

From Littledamien Wiki
Jump to navigation Jump to search

Overview[edit]

Services should be used to provide business logic for controllers.[1]

Controllers should follow a 5-10-20 rule. 5 variables, 10 actions, and 20 lines of code at a maximum for each controller. Push as much business logic to services to conform to this rule.[2]

Class locations[edit]

Business logic classes should be outside the Entity directory, but still within the bundle. Something like {project_root}\src\AppBundle\Utils\.

Creating a service (example)[edit]

  1. Create a business logic class
  2. Define the service in services.yml
  3. Use the service in a controller.

Business logic class[edit]

Defines a utility method, slugify():

// src/AppBundle/Utils/Slugger.php
namespace AppBundle\Utils;

class Slugger
{
    public function slugify($string)
    {
        return preg_replace(
            '/[^a-z0-9]/', '-', strtolower(trim(strip_tags($string)))
        );
    }
}

Define a service for the class[edit]

The naming convention traditionally is the path to the class, e.g. app.utils.slugger, but brevity is the preferred convention, so use the shortest name possible (in this case app.slugger).

# app/config/services.yml
services:
    # keep your service names short
    app.slugger:
        class: AppBundle\Utils\Slugger

Using the service[edit]

Services are accessed (in a controller for example) with the get() routine:

$slug = $this->get('app.slugger')->slugify($post->getTitle());

Notes[edit]

  1. Organizing Your Business Logic, Symfony Best Practices
  2. Controllers, Symfony Best Practices