Présentation par Vlad RIABCHENKO
Injection de dépendances dans Symfony >= 3.3
28
Nov 2017
Conteneur de services et
injection de dépendances
D I d a n s S y m f o n y > = 3 . 3
C o n t e n e u r d e s s e r v i c e s
D I d a n s S y m f o n y > = 3 . 3
Définitions Objets prêts-à-utiliser
$container->get('mailer');
$container->get('doctrine');
$container->get('app.customer');
app.customer:
class: AppBundleServiceCustomerSerivce
I n j e c t i o n d e d é p e n d a n c e s
D I d a n s S y m f o n y > = 3 . 3
But du conteneur de services:
• Garder les services et les fournir par son nom
• Instancier les services seulement à la demande
• Instancier les services en se basant sur leurs définitions
• Instancier les services en les approvisionnant de leur dépendances
app.form.user_type:
class: AppBundleFormUserType
arguments: ["@app.user"]
app.user:
class: AppBundleServiceUserService
arguments: ["@mailer"]
I n j e c t i o n d e d é p e n d a n c e s
D I d a n s S y m f o n y > = 3 . 3
app.form.user_type:
class: AppBundleFormUserType
arguments: ["@app.user"]
app.user:
class: AppBundleServiceUserService
arguments: ["@mailer"]
mailer:
class: Swift_Mailer
class UserService
{
public function __construct(Swift_Mailer $mailer)
{ }
}
class UserType
{
public function __construct(UserService $userSerivce)
{}
}
class Swift_Mailer
{ }
Autowiring
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
D I d a n s S y m f o n y > = 3 . 3
Autowiring simplifie la configuration de vos services.
Il lit les indications de type (Type-hints) sur le constructeur et passe automatiquement
les services corrects.
class UserType
{
/**
* Constructeur
*
* @param UserService $userService
* @param TokenStorageInterface $tokenStorage
* @param UrlGeneratorInterface $router
*/
public function __construct(
UserService $userService,
TokenStorageInterface $tokenStorage,
UrlGeneratorInterface $router
) { }
}
#services.yml
app.form.user_type:
class: AppBundleFormUserType
arguments:
- "@app.user"
- "@security.token_storage"
- "@router"
#services.yml
app.form.user_type:
class: AppBundleFormUserType
autowire: true
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
Il est possible de lister les services qui peuvent être autowired pour savoir quelle
classe/interfase il faut spécifier dans les paramètres de constructeur.
# php bin/console debug:container --types
------------------------------------------------------------------------------------ --------------------------------------------------------
Service ID Class name
------------------------------------------------------------------------------------ --------------------------------------------------------
AppBundleFormUserType AppBundleFormUserType
AppBundleServiceUserServiceA AppBundleServiceUserServiceA
AppBundleServiceUserServiceB AppBundleServiceUserServiceB
AppBundleServiceUserServiceInterface alias for "AppBundleServiceUserServiceA"
DoctrineCommonAnnotationsReader alias for "annotations.cached_reader"
DoctrineCommonPersistenceManagerRegistry alias for "doctrine"
DoctrineCommonPersistenceObjectManager alias for "doctrine.orm.default_entity_manager"
DoctrineDBALConnection alias for "doctrine.dbal.default_connection"
DoctrineDBALDriverConnection alias for "doctrine.dbal.default_connection"
DoctrineORMEntityManagerInterface alias for "doctrine.orm.default_entity_manager"
PsrCacheCacheItemPoolInterface alias for "cache.app"
PsrContainerContainerInterface alias for "service_container"
PsrLogLoggerInterface alias for "monolog.logger"
SessionHandlerInterface alias for "session.handler.native_file"
Swift_Mailer alias for "swiftmailer.mailer.default"
Swift_Spool alias for "swiftmailer.mailer.default.spool.memory"
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
class UserType
{
/**
* Constructeur
*
* @param UserServiceInterface $userService
*/
public function __construct(
UserServiceInterface $userService
) { }
}
Indications de type par interfaces.
(1/1) AutowiringFailedException
Cannot autowire service "app.form.user_type": argument "$userService" of
method "AppBundleFormUserType::__construct()" references interface
"AppBundleServiceUserServiceInterface" but no such service exists.
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
Nom de service = FQCN (fully qualified class name)
#services.yml
app.form.user_type:
class: AppBundleFormUserType
autowire: true
app.user.a:
class: AppBundleServiceUserServiceA
autowire: true
app.user.b:
class: AppBundleServiceUserServiceB
#services.yml
AppBundleFormUserType:
autowire: true
AppBundleServiceUserServiceA:
autowire: true
AppBundleServiceUserServiceB: ~
$this->get('app.form.user_type'); $this->get(UserType::class);
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
#services.yml
AppBundleFormUserType:
autowire: true
AppBundleServiceUserServiceA:
autowire: true
AppBundleServiceUserServiceB: ~
AppBundleServiceUserServiceInterface:
alias: "@AppBundleServiceUserServiceA"
AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
Alias est la solution pour l’indications de type par interfaces.
Scalar values (parameters)
D I d a n s S y m f o n y > = 3 . 3
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
(1/1) AutowiringFailedException
Cannot autowire service "AppBundleFormUserType": argument "$minOrder" of method "__construct()" must have a type-
hint or be given a value explicitly.
class UserType
{
/**
* Constructeur
*
* @param UserServiceInterface $userService
* @param float $minOrder
* @param int $defaultCity
*/
public function __construct(
UserServiceInterface $userService,
$minOrder,
$defaultCity
) { }
}
#services.yml
parameters:
min_order: 50.5
default_city: Paris
services:
AppBundleFormUserType:
autowire: true
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
class UserType
{
/**
* Constructeur
*
* @param UserServiceInterface $userService
* @param float $minOrder
* @param int $defaultCity
*/
public function __construct(
UserServiceInterface $userService,
$minOrder,
$defaultCity
) { }
}
#services.yml
parameters:
min_order: 50.5
default_city: Paris
services:
AppBundleFormUserType:
autowire: true
arguments:
$defaultCity: "%default_city%"
$minOrder: "%min_order%"
D I d a n s S y m f o n y > = 3 . 3
a u t o wi r e : t r u e
#services.yml
parameters:
min_order: 50.5
default_city: Paris
services:
AppBundleFormUserType:
autowire: true
arguments:
$userService: "@AppBundleServiceUserServiceB"
$defaultCity: "%default_city%"
$minOrder: "%min_order%"
AppBundleServiceUserServiceA:
autowire: true
AppBundleServiceUserServiceB: ~
AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
Notion $arg permet spécifier une valeur ou un service souhaité
Autoconfigure
D I d a n s S y m f o n y > = 3 . 3
D I d a n s S y m f o n y > = 3 . 3
a u t o c o n f i g u r e : t r u e
Option autoconfigure enregistre automatiquement vos services en tant que
commandes, event subscribers, types de formulaire etc.
#services.yml
AppBundleFormUserType:
autowire: true
autoconfigure: true
AppBundleEventListenerUserEventSubscriber:
autoconfigure: true
#services.yml
AppBundleFormUserType:
autowire: true
tags: [{name: form.type}]
AppBundleEventListenerUserEventSubscriber:
tags: [{name: kernel.event_subscriber}] class UserEventSubscriber
implements EventSubscriberInterface
{
// implementation
}
class UserType extends AbstractType
{
// implementation
}
D I d a n s S y m f o n y > = 3 . 3
a u t o c o n f i g u r e : t r u e
Autoconfigure se base sur l’instance de service en utilisant operateur instanceof.
Instance tag
FormTypeInterface tags: [form.type]
EventSubscriberInterface tags: [kernel.event_subscriber]
Twig_ExtensionInterface tags: [twig.extension]
SymfonyComponentConsoleCommandCommand tags: [console.command]
… …
D I d a n s S y m f o n y > = 3 . 3
a u t o c o n f i g u r e : t r u e
Autoconfigure fonctionne à l’aide de clé _instanceof.
#services.yml
services:
_instanceof:
AppBundleDomainLoaderInterface:
public: true
tags: ['app.domain_loader']
Tous les services implémentant ce LoaderInterface seront publics et dotés de
‘app.domain_loader’ tag si la clé autoconfigure est activée pour eux.
_defaults
D I d a n s S y m f o n y > = 3 . 3
D I d a n s S y m f o n y > = 3 . 3
_ d e f a u l t s
Clé _defaults permet de spécifier la configuration commune pour les services définis
dans un fichier.
#services.yml
services:
# default configuration for services in *this* file
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundleFormUserType: ~
AppBundleServiceUserServiceA: ~
AppBundleServiceUserServiceB: ~
AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
Déclaration groupée
D I d a n s S y m f o n y > = 3 . 3
D I d a n s S y m f o n y > = 3 . 3
D é c l a r a t i o n g r o u p é e
Déclaration groupée permet de réduire beaucoup la taille de configuration.
#services.yml
services:
# default configuration for services in *this* file
_defaults:
autowire: true
autoconfigure: true
public: true
# makes classes in src/AppBundle available to be used as services
# this creates a service per class whose id is the fully-qualified class name
AppBundle:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
Tag controller.service_arguments
D I d a n s S y m f o n y > = 3 . 3
D I d a n s S y m f o n y > = 3 . 3
Ta g c o n t r o l l e r. s e r v i c e _ a r g u m e n t s
Les contrôleurs sont dotés de controller.service_arguments tag pour faire fonctionner
l’autowiring lors d’appelle d’une action.
#services.yml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
AppBundleController:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
D I d a n s S y m f o n y > = 3 . 3
Ta g c o n t r o l l e r. s e r v i c e _ a r g u m e n t s
class DefaultController extends Controller
{
/**
* /**
* @Route("/", name="homepage")
*
* @param Request $request
* @param EntityManagerInterface $em
* @param UserServiceInterface $userService
* @param LoggerInterface $logger
*/
public function indexAction(
Request $request,
EntityManagerInterface $em,
UserServiceInterface $userService,
LoggerInterface $logger
) { }
}
R ETR OU VEZ W EBN ET
Merci
pour votre attention

More Related Content

PPTX
SOLID: the core principles of success of the Symfony web framework and of you...
PPTX
Crafting beautiful software
ODP
Symfony2, creare bundle e valore per il cliente
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
PDF
Sylius and Api Platform The story of integration
PPTX
Hacking Your Way To Better Security - Dutch PHP Conference 2016
PPT
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
KEY
Symfony2 Building on Alpha / Beta technology
SOLID: the core principles of success of the Symfony web framework and of you...
Crafting beautiful software
Symfony2, creare bundle e valore per il cliente
Rich domain model with symfony 2.5 and doctrine 2.5
Sylius and Api Platform The story of integration
Hacking Your Way To Better Security - Dutch PHP Conference 2016
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
Symfony2 Building on Alpha / Beta technology

What's hot (20)

PDF
Lithium: The Framework for People Who Hate Frameworks
PDF
Doctrine fixtures
PDF
The Zen of Lithium
PDF
Symfony World - Symfony components and design patterns
PDF
The State of Lithium
PDF
Min-Maxing Software Costs
PDF
Leveraging Symfony2 Forms
PDF
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
PDF
Writing Sensible Code
PDF
Migrating to dependency injection
PDF
Everything you always wanted to know about forms* *but were afraid to ask
PDF
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
PDF
Building Lithium Apps
PPTX
Adding Dependency Injection to Legacy Applications
PDF
Doctrine with Symfony - SymfonyCon 2019
PDF
Design Patterns in PHP5
PDF
The IoC Hydra
PDF
Min-Maxing Software Costs - Laracon EU 2015
PDF
Beyond symfony 1.2 (Symfony Camp 2008)
PDF
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Lithium: The Framework for People Who Hate Frameworks
Doctrine fixtures
The Zen of Lithium
Symfony World - Symfony components and design patterns
The State of Lithium
Min-Maxing Software Costs
Leveraging Symfony2 Forms
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Writing Sensible Code
Migrating to dependency injection
Everything you always wanted to know about forms* *but were afraid to ask
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Building Lithium Apps
Adding Dependency Injection to Legacy Applications
Doctrine with Symfony - SymfonyCon 2019
Design Patterns in PHP5
The IoC Hydra
Min-Maxing Software Costs - Laracon EU 2015
Beyond symfony 1.2 (Symfony Camp 2008)
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Ad

Similar to Injection de dépendances dans Symfony >= 3.3 (20)

PDF
Symfony2 - from the trenches
PDF
Symfony2 from the Trenches
PDF
Symfony2 revealed
PDF
What is new in Symfony 3,3, 3,4, 4.0, 4,1 + Flex
PDF
Symfony Under the Hood
PPTX
A soa approximation on symfony
PPTX
A SOA approximation on symfony
PPT
Symfony2 Service Container: Inject me, my friend
PDF
Desymfony 2011 - Habemus Bundles
PDF
Symfony internals [english]
PDF
Symfony metabook 2.0
PDF
Symfony 4: A new way to develop applications #phpsrb
PDF
Symfony 1.3 + Doctrine 1.2
PDF
The Naked Bundle - Tryout
PDF
Fabien Potencier "Symfony 4 in action"
PDF
Symfony: Your Next Microframework (SymfonyCon 2015)
PDF
Symfony 4: A new way to develop applications #ipc19
PDF
Lets play with Symfony2
PDF
Design Patterns avec PHP 5.3, Symfony et Pimple
PDF
How kris-writes-symfony-apps-london
Symfony2 - from the trenches
Symfony2 from the Trenches
Symfony2 revealed
What is new in Symfony 3,3, 3,4, 4.0, 4,1 + Flex
Symfony Under the Hood
A soa approximation on symfony
A SOA approximation on symfony
Symfony2 Service Container: Inject me, my friend
Desymfony 2011 - Habemus Bundles
Symfony internals [english]
Symfony metabook 2.0
Symfony 4: A new way to develop applications #phpsrb
Symfony 1.3 + Doctrine 1.2
The Naked Bundle - Tryout
Fabien Potencier "Symfony 4 in action"
Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony 4: A new way to develop applications #ipc19
Lets play with Symfony2
Design Patterns avec PHP 5.3, Symfony et Pimple
How kris-writes-symfony-apps-london
Ad

More from Vladyslav Riabchenko (7)

PPTX
Modèle de domaine riche dans une application métier complexe un exemple pratique
PPTX
SOLID : les principes à l’origine du succès de Symfony et de vos applications
PPTX
Sécurisation de vos applications web à l’aide du composant Security de Symfony
PPTX
Sécurisation de vos applications web à l’aide du composant Security de Symfony
PPTX
Versionning sémantique et Composer
PPTX
Les patrons de conception du composant Form
Modèle de domaine riche dans une application métier complexe un exemple pratique
SOLID : les principes à l’origine du succès de Symfony et de vos applications
Sécurisation de vos applications web à l’aide du composant Security de Symfony
Sécurisation de vos applications web à l’aide du composant Security de Symfony
Versionning sémantique et Composer
Les patrons de conception du composant Form

Recently uploaded (20)

PDF
Guide to Food Delivery App Development.pdf
PPTX
Computer Software - Technology and Livelihood Education
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
iTop VPN Crack Latest Version Full Key 2025
PPTX
Cybersecurity: Protecting the Digital World
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
PPTX
Introduction to Windows Operating System
PPTX
Matchmaking for JVMs: How to Pick the Perfect GC Partner
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PPTX
CNN LeNet5 Architecture: Neural Networks
PPTX
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
PDF
Wondershare Recoverit Full Crack New Version (Latest 2025)
DOC
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PPTX
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
DOCX
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
PDF
Microsoft Office 365 Crack Download Free
PPTX
Trending Python Topics for Data Visualization in 2025
Guide to Food Delivery App Development.pdf
Computer Software - Technology and Livelihood Education
Advanced SystemCare Ultimate Crack + Portable (2025)
iTop VPN Crack Latest Version Full Key 2025
Cybersecurity: Protecting the Digital World
CCleaner 6.39.11548 Crack 2025 License Key
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
Introduction to Windows Operating System
Matchmaking for JVMs: How to Pick the Perfect GC Partner
How Tridens DevSecOps Ensures Compliance, Security, and Agility
CNN LeNet5 Architecture: Neural Networks
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
Wondershare Recoverit Full Crack New Version (Latest 2025)
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
Microsoft Office 365 Crack Download Free
Trending Python Topics for Data Visualization in 2025

Injection de dépendances dans Symfony >= 3.3

  • 1. Présentation par Vlad RIABCHENKO Injection de dépendances dans Symfony >= 3.3 28 Nov 2017
  • 2. Conteneur de services et injection de dépendances D I d a n s S y m f o n y > = 3 . 3
  • 3. C o n t e n e u r d e s s e r v i c e s D I d a n s S y m f o n y > = 3 . 3 Définitions Objets prêts-à-utiliser $container->get('mailer'); $container->get('doctrine'); $container->get('app.customer'); app.customer: class: AppBundleServiceCustomerSerivce
  • 4. I n j e c t i o n d e d é p e n d a n c e s D I d a n s S y m f o n y > = 3 . 3 But du conteneur de services: • Garder les services et les fournir par son nom • Instancier les services seulement à la demande • Instancier les services en se basant sur leurs définitions • Instancier les services en les approvisionnant de leur dépendances app.form.user_type: class: AppBundleFormUserType arguments: ["@app.user"] app.user: class: AppBundleServiceUserService arguments: ["@mailer"]
  • 5. I n j e c t i o n d e d é p e n d a n c e s D I d a n s S y m f o n y > = 3 . 3 app.form.user_type: class: AppBundleFormUserType arguments: ["@app.user"] app.user: class: AppBundleServiceUserService arguments: ["@mailer"] mailer: class: Swift_Mailer class UserService { public function __construct(Swift_Mailer $mailer) { } } class UserType { public function __construct(UserService $userSerivce) {} } class Swift_Mailer { }
  • 6. Autowiring D I d a n s S y m f o n y > = 3 . 3
  • 7. a u t o wi r e : t r u e D I d a n s S y m f o n y > = 3 . 3 Autowiring simplifie la configuration de vos services. Il lit les indications de type (Type-hints) sur le constructeur et passe automatiquement les services corrects. class UserType { /** * Constructeur * * @param UserService $userService * @param TokenStorageInterface $tokenStorage * @param UrlGeneratorInterface $router */ public function __construct( UserService $userService, TokenStorageInterface $tokenStorage, UrlGeneratorInterface $router ) { } } #services.yml app.form.user_type: class: AppBundleFormUserType arguments: - "@app.user" - "@security.token_storage" - "@router" #services.yml app.form.user_type: class: AppBundleFormUserType autowire: true
  • 8. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e Il est possible de lister les services qui peuvent être autowired pour savoir quelle classe/interfase il faut spécifier dans les paramètres de constructeur. # php bin/console debug:container --types ------------------------------------------------------------------------------------ -------------------------------------------------------- Service ID Class name ------------------------------------------------------------------------------------ -------------------------------------------------------- AppBundleFormUserType AppBundleFormUserType AppBundleServiceUserServiceA AppBundleServiceUserServiceA AppBundleServiceUserServiceB AppBundleServiceUserServiceB AppBundleServiceUserServiceInterface alias for "AppBundleServiceUserServiceA" DoctrineCommonAnnotationsReader alias for "annotations.cached_reader" DoctrineCommonPersistenceManagerRegistry alias for "doctrine" DoctrineCommonPersistenceObjectManager alias for "doctrine.orm.default_entity_manager" DoctrineDBALConnection alias for "doctrine.dbal.default_connection" DoctrineDBALDriverConnection alias for "doctrine.dbal.default_connection" DoctrineORMEntityManagerInterface alias for "doctrine.orm.default_entity_manager" PsrCacheCacheItemPoolInterface alias for "cache.app" PsrContainerContainerInterface alias for "service_container" PsrLogLoggerInterface alias for "monolog.logger" SessionHandlerInterface alias for "session.handler.native_file" Swift_Mailer alias for "swiftmailer.mailer.default" Swift_Spool alias for "swiftmailer.mailer.default.spool.memory"
  • 9. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e class UserType { /** * Constructeur * * @param UserServiceInterface $userService */ public function __construct( UserServiceInterface $userService ) { } } Indications de type par interfaces. (1/1) AutowiringFailedException Cannot autowire service "app.form.user_type": argument "$userService" of method "AppBundleFormUserType::__construct()" references interface "AppBundleServiceUserServiceInterface" but no such service exists.
  • 10. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e Nom de service = FQCN (fully qualified class name) #services.yml app.form.user_type: class: AppBundleFormUserType autowire: true app.user.a: class: AppBundleServiceUserServiceA autowire: true app.user.b: class: AppBundleServiceUserServiceB #services.yml AppBundleFormUserType: autowire: true AppBundleServiceUserServiceA: autowire: true AppBundleServiceUserServiceB: ~ $this->get('app.form.user_type'); $this->get(UserType::class);
  • 11. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e #services.yml AppBundleFormUserType: autowire: true AppBundleServiceUserServiceA: autowire: true AppBundleServiceUserServiceB: ~ AppBundleServiceUserServiceInterface: alias: "@AppBundleServiceUserServiceA" AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA" Alias est la solution pour l’indications de type par interfaces.
  • 12. Scalar values (parameters) D I d a n s S y m f o n y > = 3 . 3
  • 13. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e (1/1) AutowiringFailedException Cannot autowire service "AppBundleFormUserType": argument "$minOrder" of method "__construct()" must have a type- hint or be given a value explicitly. class UserType { /** * Constructeur * * @param UserServiceInterface $userService * @param float $minOrder * @param int $defaultCity */ public function __construct( UserServiceInterface $userService, $minOrder, $defaultCity ) { } } #services.yml parameters: min_order: 50.5 default_city: Paris services: AppBundleFormUserType: autowire: true
  • 14. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e class UserType { /** * Constructeur * * @param UserServiceInterface $userService * @param float $minOrder * @param int $defaultCity */ public function __construct( UserServiceInterface $userService, $minOrder, $defaultCity ) { } } #services.yml parameters: min_order: 50.5 default_city: Paris services: AppBundleFormUserType: autowire: true arguments: $defaultCity: "%default_city%" $minOrder: "%min_order%"
  • 15. D I d a n s S y m f o n y > = 3 . 3 a u t o wi r e : t r u e #services.yml parameters: min_order: 50.5 default_city: Paris services: AppBundleFormUserType: autowire: true arguments: $userService: "@AppBundleServiceUserServiceB" $defaultCity: "%default_city%" $minOrder: "%min_order%" AppBundleServiceUserServiceA: autowire: true AppBundleServiceUserServiceB: ~ AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA" Notion $arg permet spécifier une valeur ou un service souhaité
  • 16. Autoconfigure D I d a n s S y m f o n y > = 3 . 3
  • 17. D I d a n s S y m f o n y > = 3 . 3 a u t o c o n f i g u r e : t r u e Option autoconfigure enregistre automatiquement vos services en tant que commandes, event subscribers, types de formulaire etc. #services.yml AppBundleFormUserType: autowire: true autoconfigure: true AppBundleEventListenerUserEventSubscriber: autoconfigure: true #services.yml AppBundleFormUserType: autowire: true tags: [{name: form.type}] AppBundleEventListenerUserEventSubscriber: tags: [{name: kernel.event_subscriber}] class UserEventSubscriber implements EventSubscriberInterface { // implementation } class UserType extends AbstractType { // implementation }
  • 18. D I d a n s S y m f o n y > = 3 . 3 a u t o c o n f i g u r e : t r u e Autoconfigure se base sur l’instance de service en utilisant operateur instanceof. Instance tag FormTypeInterface tags: [form.type] EventSubscriberInterface tags: [kernel.event_subscriber] Twig_ExtensionInterface tags: [twig.extension] SymfonyComponentConsoleCommandCommand tags: [console.command] … …
  • 19. D I d a n s S y m f o n y > = 3 . 3 a u t o c o n f i g u r e : t r u e Autoconfigure fonctionne à l’aide de clé _instanceof. #services.yml services: _instanceof: AppBundleDomainLoaderInterface: public: true tags: ['app.domain_loader'] Tous les services implémentant ce LoaderInterface seront publics et dotés de ‘app.domain_loader’ tag si la clé autoconfigure est activée pour eux.
  • 20. _defaults D I d a n s S y m f o n y > = 3 . 3
  • 21. D I d a n s S y m f o n y > = 3 . 3 _ d e f a u l t s Clé _defaults permet de spécifier la configuration commune pour les services définis dans un fichier. #services.yml services: # default configuration for services in *this* file _defaults: autowire: true autoconfigure: true public: false AppBundleFormUserType: ~ AppBundleServiceUserServiceA: ~ AppBundleServiceUserServiceB: ~ AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
  • 22. Déclaration groupée D I d a n s S y m f o n y > = 3 . 3
  • 23. D I d a n s S y m f o n y > = 3 . 3 D é c l a r a t i o n g r o u p é e Déclaration groupée permet de réduire beaucoup la taille de configuration. #services.yml services: # default configuration for services in *this* file _defaults: autowire: true autoconfigure: true public: true # makes classes in src/AppBundle available to be used as services # this creates a service per class whose id is the fully-qualified class name AppBundle: resource: '../../src/AppBundle/*' exclude: '../../src/AppBundle/{Entity,Repository,Tests}' AppBundleServiceUserServiceInterface: "@AppBundleServiceUserServiceA"
  • 24. Tag controller.service_arguments D I d a n s S y m f o n y > = 3 . 3
  • 25. D I d a n s S y m f o n y > = 3 . 3 Ta g c o n t r o l l e r. s e r v i c e _ a r g u m e n t s Les contrôleurs sont dotés de controller.service_arguments tag pour faire fonctionner l’autowiring lors d’appelle d’une action. #services.yml services: _defaults: autowire: true autoconfigure: true public: false AppBundle: resource: '../../src/AppBundle/*' exclude: '../../src/AppBundle/{Entity,Repository,Tests}' # controllers are imported separately to make sure they're public # and have a tag that allows actions to type-hint services AppBundleController: resource: '../../src/AppBundle/Controller' public: true tags: ['controller.service_arguments']
  • 26. D I d a n s S y m f o n y > = 3 . 3 Ta g c o n t r o l l e r. s e r v i c e _ a r g u m e n t s class DefaultController extends Controller { /** * /** * @Route("/", name="homepage") * * @param Request $request * @param EntityManagerInterface $em * @param UserServiceInterface $userService * @param LoggerInterface $logger */ public function indexAction( Request $request, EntityManagerInterface $em, UserServiceInterface $userService, LoggerInterface $logger ) { } }
  • 27. R ETR OU VEZ W EBN ET Merci pour votre attention