You are on page 1of 2

The way you can re-use By https://andreiabohner.

org
code in Symfony

Services The command:


$ php bin/console debug:autowiring
list all services available

4.2
Fetching and using services for autowiring

There are 2 ways:


can be used as
type-hints in your
methods/constructors
Some autowirable services available
1. Autowirable services Internally, each service
has a unique
when there´s more than one type
hint for one service id, you can use
name, or "id" either to get the exact same object
By default, all services you
create are autowirable Service Id Service Type Hint
Creating a service
cache.app CacheItemPoolInterface
A service is just a class that does work! AdapterInterface
When you create your services (you can name it and put the
cache.app.simple CacheInterface
code wherever you want) they are also automatically added
doctrine.dbal.default_connection Connection
in the container and available for autowiring!
service_container ContainerInterface
debug.event_dispatcher EventDispatcherInterface
Using a service debug.file_link_formatter FileLinkFormatter
doctrine ManagerRegistry
In your controller, or in your own classes, you can "ask" for a service
doctrine.orm.default_entity_manager EntityManagerInterface
from the container by type-hinting an argument with the service's class
file_locator FileLocator
or interface name.
filesystem Filesystem
// src/Controller/ProductController.php http_kernel HttpKernelInterface
kernel KernelInterface
use Psr\Log\LoggerInterface; monolog.logger LoggerInterface
Symfony will
automatically pass doctrine.orm.default_entity_manager ObjectManager
/**
the service object annotations.cached_reader Reader
* @Route("/products")
matching this type parameter_bag ParameterBagInterface
*/
public function list(LoggerInterface $logger) ContainerBagInterface
{ request_stack RequestStack
$logger->info('Look! I just used a service'); router.default UrlGeneratorInterface
UrlMatcherInterface
// ... RequestContextAwareInterface
} RouterInterface
router.request_context RequestContext
Adding dependencies in your service serializer DecoderInterface
EncoderInterface
use Symfony\Component\Cache\Adapter\AdapterInterface; SerializerInterface
Just pass them via NormalizerInterface
class MyService constructor! DenormalizerInterface
{ The constructor’s serializer.normalizer.object ObjectNormalizer
private $cache; arguments are autowired! session.handler SessionHandlerInterface
public function __construct(AdapterInterface $cache) service_container ContainerInterface
{ session SessionInterface
$this->cache = $cache; session.flash_bag FlashBagInterface
} session.storage.native SessionStorageInterface
twig Twig_Environment
// ... Environment
}

2. Explicitly configuring services and arguments


# config/services.yaml
services:
Fetching a non-standard service
service's id
Access core services that cannot be autowired in your service
site_update_manager.superadmin: via arguments:
class: App\Updates\SiteUpdateManager disable autowire services:
autowire: false for this service App\Service\MyService:
manually arguments: arguments:
wire all - '@App\Service\MessageGenerator' $logger: '@monolog.logger.email'
arguments - '@mailer'
- 'superadmin@example.com'
@ - used to pass the service
with that id
site_update_manager.normal_users:
class: App\Updates\SiteUpdateManager
autowire: false Create an alias, so if you
arguments: type-hint SiteUpdateManager,
- '@App\Service\MessageGenerator' the site_update_manager.superadmin
- '@mailer' will be used
- 'contact@example.com'

App\Updates\SiteUpdateManager: '@site_update_manager.superadmin'
By https://andreiabohner.org
A class that does work

Services all services are shared by default


(i.e., each time you retrieve the service,
you'll get the same instance)

4.2 Default configuration for services


All configurations below comes standard with every new Symfony project

config under services default config values that should be


will affect all services # config/services.yaml applied to all services registered in this file
in the application services:
_defaults: automatically injects dependencies
in your services
automatically autowire: true
registers your services autoconfigure: true allows optimizing the container by removing unused services;
as commands, fetching services directly from the container
event subscribers, ... public: false via $container->get() won't work

makes classes in src/ App\:


available to be used resource: '../src/*' can be any valid glob pattern
as services, this creates
a service per class exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
whose id is the FQCN

is responsible
for instantiating
all the services where all
services live!
Service Container When you start a E.g. of services:
Services are never instantiated until, and unless, someone asks for them. Symfony app, your log security
Each service in the container is instantiated a maximum of once per request. container already email cache
contains many services. database session

Other configuration for services


# config/services.yaml
services:
anonymous service:
App\Foo: - prevent a service being used as a dependency of other services
arguments: - don't define an ID
- created where is used
- !service
class: App\AnonymousBar

App\Service\OldService:
deprecating deprecated: The "%service_id%" is deprecated since 2.8 and will be removed in 3.0.
a service

App\SomeNonSharedService: non shared service:


whenever you request the App\SomeNonSharedService,
shared: false you will always get a new instance

App\Service\EmailHelper: disable autowire to this service


autowire: false (override the default config just for this service)
you can put the
bind key under if find any argument named
bind: $emailLogger, the monolog.logger.email
_defaults, services,
or a specific service $emailLogger: '@monolog.logger.email' will be passed to it
Some\Service: '@some.service'
you can bind by:
public function __construct(LoggerInterface $emailLogger)
- argument name
- class or interface {
- both above $this->logger = $emailLogger;
}

Console
$ php bin/console debug:autowiring show all services available for autowiring
$ php bin/console debug:container full list of services available in the container
$ php bin/console debug:container 'App\Service\Mailer' detailed info about a single service (you can use the service id too)
$ php bin/console debug:container 'App\Service\Mailer' --show-arguments show the service arguments
$ php bin/console debug:container --show-hidden display “hidden services” (whose ID starts with a dot)

You might also like