Symfony Services Cookbook: Difference between revisions
Jump to navigation
Jump to search
(Created page with "Category:Symfony Category:PHP Category:Web Development == Overview == Services should be used to provide business logic for controllers.<ref>[http://symfony.com/d...") |
(No difference)
|
Latest revision as of 20:57, 6 February 2015
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]
- Create a business logic class
- Define the service in
services.yml - 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]
- ↑ Organizing Your Business Logic, Symfony Best Practices
- ↑ Controllers, Symfony Best Practices