Services
Dependency Injection, Services
Table of Contents
• Dependency Injection
• Symfony Services
• Controller as a Service
2
DEPENDENCY INJECTION
Dependency Injection
• Dependency injection is a software design pattern in witch one or
more dependencies (or services) are injected, or passed by
reference, into a dependent object (or client) and are made part of
the client’s
state.
• The pattern separates the creation of a client’s dependencies from
its own behavior, witch allows program designs to be loosely coupled
and to follow the dependency inversion and single responsibility
principles.
• In directly contrasts with the service locator pattern, witch allows
clients to know about the system they use to find dependencies.
Controller
5
Problems of the code
• Name of the author is out of scope of the question
• Author is tightly coupled with the Question
• Unit Testing becomes difficult
6
INJECT ALL DEPENDENCIES!
Controller
8
Benefits
• Reduces complexity
• Improves quality
• Eases unit testing
9
Using constructor injection
• Strictly defines the requirements
• Dependencies cannot be changed
Except…
• Does not work with optional dependencies
• Inheritance can become difficult
Solution ?
10
Setter Injection
• Allows creating an object with
the default values
• Allows easy insertion of new
optional dependencies
11
SYMFONY SERVICES
What is Service
• Useful objects not directly related your application logic
Inject Use CRUD
Controller Services ORM
Database
Defining our own services
14
SYMFONY SERVICES EXAMPLE
countries_mysql.sql
MyController.php
CountryService.php
CountryRepository.php
Result
CONTROLLER AS A SERVICE
Controller as a Service
• Controller and passed services can be controller by a
container
configuration
• Sandboxing the controller
• Easily spotting "fat" controllers
Creating the controller as a service
Drawbacks
• More work to create
• Complex constructor
• More work to create methods defined in the base
controller
Summary
§ Dependency Injection
§ Symfony Services
§ Controller as a Service
25