Symfony y los bundles de terceros configuran y obtienen sus services a través del container, por lo que puedes acceder a ellos o usarlos en tus propios services. Symfony por defecto no requiere que los controllers se definan como services, e inyecta el service container en los controllers. Por ejemplo, para manejar la información de almacenamiento de la sesión de un usuario, Symfony proporciona un service session, al que puedes acceder desde un controller normal:
public function indexAction($bar)
{
$session = $this->get('session');
$session->set('foo', $bar);
// ...
}
En Symfony se emplean continuamente services proporcionados por el core de Symfony o por bundles de terceros para hacer tareas como renderizar templates (templating), enviar emails (mailer), o acceder a información del request (request).
Puedes también emplear estos services dentro de services que hayas creado para tu aplicación. Vamos a utilizar el Symfony mailer service para una clase NewsletterManager, y pasaremos el templating service a la misma clase para que pueda generar el contenido del email a través de una template:
// src/AppBundle/Newsletter/NewsletterManager.php
namespace AppBundle\Newsletter;
use Symfony\Component\Templating\EngineInterface;
class NewsletterManager
{
protected $mailer;
protected $templating;
public function __construct(\Swift_Mailer $mailer, EngineInterface $templating)
{
$this->mailer = $mailer;
$this->templating = $templating;
}
// ...
}
Ahora podemos introducir las dependencias en el service:
# app/config/services.yml
services:
app.newsletter_manager:
class: AppBundle\Newsletter\NewsletterManager
arguments: ['@mailer', '@templating']
El service _app.newslettermanager ahora tiene acceso a los core services mailer y templating.
Podemos mostrar un listado de todos los services (y sus clases) que están registrados en el container con la consola, con el siguiente comando:
php bin/console debug:container
Por defecto sólo se muestran public services, pero puedes también ver private services con
php bin/console debug:container --show-private
Listado completo de services disponibles en Symfony 3
- annotation_reader Doctrine\Common\Annotations\CachedReader
- assets.context Symfony\Component\Asset\Context\RequestStackContext
- assets.packages Symfony\Component\Asset\Packages
- cache_clearer Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer
- cache_warmer Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate
- config_cache_factory Symfony\Component\Config\ResourceCheckerConfigCacheFactory
- console.command.sensiolabs_security_command_securitycheckercommand alias for "sensio_distribution.security_checker.command"
- data_collector.dump Symfony\Component\HttpKernel\DataCollector\DumpDataCollector
- data_collector.form Symfony\Component\Form\Extension\DataCollector\FormDataCollector
- data_collector.form.extractor Symfony\Component\Form\Extension\DataCollector\FormDataExtractor
- data_collector.request Symfony\Component\HttpKernel\DataCollector\RequestDataCollector
- data_collector.router Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector
- database_connection alias for "doctrine.dbal.default_connection"
- debug.controller_resolver Symfony\Component\HttpKernel\Controller\TraceableControllerResolver
- debug.debug_handlers_listener Symfony\Component\HttpKernel\EventListener\DebugHandlersListener
- debug.dump_listener Symfony\Component\HttpKernel\EventListener\DumpListener
- debug.event_dispatcher Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher
- debug.stopwatch Symfony\Component\Stopwatch\Stopwatch doctrine Doctrine\Bundle\DoctrineBundle\Registry
- doctrine.dbal.connection_factory Doctrine\Bundle\DoctrineBundle\ConnectionFactory
- doctrine.dbal.default_connection Doctrine\DBAL\Connection
- doctrine.orm.default_entity_listener_resolver Doctrine\ORM\Mapping\DefaultEntityListenerResolver
- doctrine.orm.default_entity_manager Doctrine\ORM\EntityManager
- doctrine.orm.default_listeners.attach_entity_listeners Doctrine\ORM\Tools\AttachEntityListenersListener
- doctrine.orm.default_manager_configurator Doctrine\Bundle\DoctrineBundle\ManagerConfigurator
- doctrine.orm.default_metadata_cache alias for "doctrine_cache.providers.doctrine.orm.default_metadata_cache"
- doctrine.orm.default_query_cache alias for "doctrine_cache.providers.doctrine.orm.default_query_cache"
- doctrine.orm.default_result_cache alias for "doctrine_cache.providers.doctrine.orm.default_result_cache"
- doctrine.orm.entity_manager alias for "doctrine.orm.default_entity_manager"
- doctrine.orm.validator.unique Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator
- doctrine.orm.validator_initializer Symfony\Bridge\Doctrine\Validator\DoctrineInitializer
- doctrine_cache.providers.doctrine.orm.default_metadata_cache Doctrine\Common\Cache\ArrayCache
- doctrine_cache.providers.doctrine.orm.default_query_cache Doctrine\Common\Cache\ArrayCache
- doctrine_cache.providers.doctrine.orm.default_result_cache Doctrine\Common\Cache\ArrayCache
- event_dispatcher alias for "debug.event_dispatcher"
- file_locator Symfony\Component\HttpKernel\Config\FileLocator
- filesystem Symfony\Component\Filesystem\Filesystem
- form.factory Symfony\Component\Form\FormFactory
- form.registry Symfony\Component\Form\FormRegistry
- form.resolved_type_factory Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeFactoryDataCollectorProxy
- form.type.birthday Symfony\Component\Form\Extension\Core\Type\BirthdayType
- form.type.button Symfony\Component\Form\Extension\Core\Type\ButtonType
- form.type.checkbox Symfony\Component\Form\Extension\Core\Type\CheckboxType
- form.type.choice Symfony\Component\Form\Extension\Core\Type\ChoiceType
- form.type.collection Symfony\Component\Form\Extension\Core\Type\CollectionType
- form.type.country Symfony\Component\Form\Extension\Core\Type\CountryType
- form.type.currency Symfony\Component\Form\Extension\Core\Type\CurrencyType
- form.type.date Symfony\Component\Form\Extension\Core\Type\DateType
- form.type.datetime Symfony\Component\Form\Extension\Core\Type\DateTimeType
- form.type.email Symfony\Component\Form\Extension\Core\Type\EmailType
- form.type.entity Symfony\Bridge\Doctrine\Form\Type\EntityType
- form.type.file Symfony\Component\Form\Extension\Core\Type\FileType
- form.type.form Symfony\Component\Form\Extension\Core\Type\FormType
- form.type.hidden Symfony\Component\Form\Extension\Core\Type\HiddenType
- form.type.integer Symfony\Component\Form\Extension\Core\Type\IntegerType
- form.type.language Symfony\Component\Form\Extension\Core\Type\LanguageType
- form.type.locale Symfony\Component\Form\Extension\Core\Type\LocaleType
- form.type.money Symfony\Component\Form\Extension\Core\Type\MoneyType
- form.type.number Symfony\Component\Form\Extension\Core\Type\NumberType
- form.type.password Symfony\Component\Form\Extension\Core\Type\PasswordType
- form.type.percent Symfony\Component\Form\Extension\Core\Type\PercentType
- form.type.radio Symfony\Component\Form\Extension\Core\Type\RadioType
- form.type.range Symfony\Component\Form\Extension\Core\Type\RangeType
- form.type.repeated Symfony\Component\Form\Extension\Core\Type\RepeatedType
- form.type.reset Symfony\Component\Form\Extension\Core\Type\ResetType
- form.type.search Symfony\Component\Form\Extension\Core\Type\SearchType
- form.type.submit Symfony\Component\Form\Extension\Core\Type\SubmitType
- form.type.text Symfony\Component\Form\Extension\Core\Type\TextType
- form.type.textarea Symfony\Component\Form\Extension\Core\Type\TextareaType
- form.type.time Symfony\Component\Form\Extension\Core\Type\TimeType
- form.type.timezone Symfony\Component\Form\Extension\Core\Type\TimezoneType
- form.type.url Symfony\Component\Form\Extension\Core\Type\UrlType
- form.type_extension.csrf Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension
- form.type_extension.form.data_collector Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension
- form.type_extension.form.http_foundation Symfony\Component\Form\Extension\HttpFoundation\Type\FormTypeHttpFoundationExtension
- form.type_extension.form.validator Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension
- form.type_extension.repeated.validator Symfony\Component\Form\Extension\Validator\Type\RepeatedTypeValidatorExtension
- form.type_extension.submit.validator Symfony\Component\Form\Extension\Validator\Type\SubmitTypeValidatorExtension
- form.type_guesser.doctrine Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser
- form.type_guesser.validator Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser
- fragment.handler Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler
- fragment.listener Symfony\Component\HttpKernel\EventListener\FragmentListener
- fragment.renderer.esi Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer
- fragment.renderer.hinclude Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer
- fragment.renderer.inline Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer
- fragment.renderer.ssi Symfony\Component\HttpKernel\Fragment\SsiFragmentRenderer
- http_kernel Symfony\Component\HttpKernel\HttpKernel
- kernel
- kernel.class_cache.cache_warmer Symfony\Bundle\FrameworkBundle\CacheWarmer\ClassCacheCacheWarmer
- locale_listener Symfony\Component\HttpKernel\EventListener\LocaleListener logger Symfony\Bridge\Monolog\Logger
- mailer alias for "swiftmailer.mailer.default"
- monolog.handler.console Symfony\Bridge\Monolog\Handler\ConsoleHandler
- monolog.handler.debug Symfony\Bridge\Monolog\Handler\DebugHandler
- monolog.handler.main Monolog\Handler\StreamHandler
- monolog.logger.doctrine Symfony\Bridge\Monolog\Logger
- monolog.logger.event Symfony\Bridge\Monolog\Logger
- monolog.logger.php Symfony\Bridge\Monolog\Logger
- monolog.logger.profiler Symfony\Bridge\Monolog\Logger
- monolog.logger.request Symfony\Bridge\Monolog\Logger
- monolog.logger.router Symfony\Bridge\Monolog\Logger
- monolog.logger.security Symfony\Bridge\Monolog\Logger
- monolog.logger.templating Symfony\Bridge\Monolog\Logger
- monolog.logger.translation Symfony\Bridge\Monolog\Logger
- profiler Symfony\Component\HttpKernel\Profiler\Profiler
- profiler_listener Symfony\Component\HttpKernel\EventListener\ProfilerListener
- property_accessor Symfony\Component\PropertyAccess\PropertyAccessor
- request_stack Symfony\Component\HttpFoundation\RequestStack
- response_listener Symfony\Component\HttpKernel\EventListener\ResponseListener
- router Symfony\Bundle\FrameworkBundle\Routing\Router
- router_listener Symfony\Component\HttpKernel\EventListener\RouterListener
- routing.loader Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader
- security.authentication.guard_handler Symfony\Component\Security\Guard\GuardAuthenticatorHandler
- security.authentication_utils Symfony\Component\Security\Http\Authentication\AuthenticationUtils
- security.authorization_checker Symfony\Component\Security\Core\Authorization\AuthorizationChecker
- security.csrf.token_manager Symfony\Component\Security\Csrf\CsrfTokenManager
- security.encoder_factory Symfony\Component\Security\Core\Encoder\EncoderFactory
- security.firewall Symfony\Component\Security\Http\Firewall
- security.firewall.map.context.dev Symfony\Bundle\SecurityBundle\Security\FirewallContext
- security.firewall.map.context.main Symfony\Bundle\SecurityBundle\Security\FirewallContext
- security.password_encoder Symfony\Component\Security\Core\Encoder\UserPasswordEncoder
- security.rememberme.response_listener Symfony\Component\Security\Http\RememberMe\ResponseListener
- security.token_storage Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage
- security.user_checker.main Symfony\Component\Security\Core\User\UserChecker
- security.validator.user_password Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator
- sensio_distribution.security_checker SensioLabs\Security\SecurityChecker
- sensio_distribution.security_checker.command SensioLabs\Security\Command\SecurityCheckerCommand
- sensio_framework_extra.cache.listener Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener
- sensio_framework_extra.controller.listener Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener
- sensio_framework_extra.converter.datetime Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DateTimeParamConverter
- sensio_framework_extra.converter.doctrine.orm Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter
- sensio_framework_extra.converter.listener Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener
- sensio_framework_extra.converter.manager Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager
- sensio_framework_extra.security.listener Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener
- sensio_framework_extra.view.guesser Sensio\Bundle\FrameworkExtraBundle\Templating\TemplateGuesser
- sensio_framework_extra.view.listener Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener
- service_container
- session Symfony\Component\HttpFoundation\Session\Session
- session.save_listener Symfony\Component\HttpKernel\EventListener\SaveSessionListener
- session.storage alias for "session.storage.native"
- session.storage.filesystem Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage
- session.storage.native Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage
- session.storage.php_bridge Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage
- session_listener Symfony\Bundle\FrameworkBundle\EventListener\SessionListener
- streamed_response_listener Symfony\Component\HttpKernel\EventListener\StreamedResponseListener
- swiftmailer.email_sender.listener Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener
- swiftmailer.mailer alias for "swiftmailer.mailer.default"
- swiftmailer.mailer.default Swift_Mailer
- swiftmailer.mailer.default.plugin.messagelogger Swift_Plugins_MessageLogger
- swiftmailer.mailer.default.spool Swift_MemorySpool
- swiftmailer.mailer.default.transport Swift_Transport_SpoolTransport
- swiftmailer.mailer.default.transport.real Swift_Transport_EsmtpTransport
- swiftmailer.plugin.messagelogger alias for "swiftmailer.mailer.default.plugin.messagelogger"
- swiftmailer.spool alias for "swiftmailer.mailer.default.spool"
- swiftmailer.transport alias for "swiftmailer.mailer.default.transport"
- swiftmailer.transport.real alias for "swiftmailer.mailer.default.transport.real"
- templating Symfony\Bundle\TwigBundle\TwigEngine
- templating.filename_parser Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser
- templating.helper.logout_url Symfony\Bundle\SecurityBundle\Templating\Helper\LogoutUrlHelper
- templating.helper.security Symfony\Bundle\SecurityBundle\Templating\Helper\SecurityHelper
- templating.loader Symfony\Bundle\FrameworkBundle\Templating\Loader\FilesystemLoader
- templating.name_parser Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser
- translation.dumper.csv Symfony\Component\Translation\Dumper\CsvFileDumper
- translation.dumper.ini Symfony\Component\Translation\Dumper\IniFileDumper
- translation.dumper.json Symfony\Component\Translation\Dumper\JsonFileDumper
- translation.dumper.mo Symfony\Component\Translation\Dumper\MoFileDumper
- translation.dumper.php Symfony\Component\Translation\Dumper\PhpFileDumper
- translation.dumper.po Symfony\Component\Translation\Dumper\PoFileDumper
- translation.dumper.qt Symfony\Component\Translation\Dumper\QtFileDumper
- translation.dumper.res Symfony\Component\Translation\Dumper\IcuResFileDumper
- translation.dumper.xliff Symfony\Component\Translation\Dumper\XliffFileDumper
- translation.dumper.yml Symfony\Component\Translation\Dumper\YamlFileDumper
- translation.extractor Symfony\Component\Translation\Extractor\ChainExtractor
- translation.extractor.php Symfony\Bundle\FrameworkBundle\Translation\PhpExtractor
- translation.loader Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader
- translation.loader.csv Symfony\Component\Translation\Loader\CsvFileLoader
- translation.loader.dat Symfony\Component\Translation\Loader\IcuDatFileLoader
- translation.loader.ini Symfony\Component\Translation\Loader\IniFileLoader
- translation.loader.json Symfony\Component\Translation\Loader\JsonFileLoader
- translation.loader.mo Symfony\Component\Translation\Loader\MoFileLoader
- translation.loader.php Symfony\Component\Translation\Loader\PhpFileLoader
- translation.loader.po Symfony\Component\Translation\Loader\PoFileLoader
- translation.loader.qt Symfony\Component\Translation\Loader\QtFileLoader
- translation.loader.res Symfony\Component\Translation\Loader\IcuResFileLoader
- translation.loader.xliff Symfony\Component\Translation\Loader\XliffFileLoader
- translation.loader.yml Symfony\Component\Translation\Loader\YamlFileLoader
- translation.writer Symfony\Component\Translation\Writer\TranslationWriter
- translator Symfony\Component\Translation\IdentityTranslator
- translator.default Symfony\Bundle\FrameworkBundle\Translation\Translator
- translator_listener Symfony\Component\HttpKernel\EventListener\TranslatorListener
- twig Twig_Environment
- twig.controller.exception Symfony\Bundle\TwigBundle\Controller\ExceptionController
- twig.controller.preview_error Symfony\Bundle\TwigBundle\Controller\PreviewErrorController
- twig.exception_listener Symfony\Component\HttpKernel\EventListener\ExceptionListener
- twig.loader Symfony\Bundle\TwigBundle\Loader\FilesystemLoader
- twig.profile Twig_Profiler_Profile
- twig.translation.extractor Symfony\Bridge\Twig\Translation\TwigExtractor
- uri_signer Symfony\Component\HttpKernel\UriSigner
- validator Symfony\Component\Validator\Validator\ValidatorInterface
- validator.builder Symfony\Component\Validator\ValidatorBuilderInterface
- validator.email Symfony\Component\Validator\Constraints\EmailValidator
- validator.expression Symfony\Component\Validator\Constraints\ExpressionValidator
- var_dumper.cli_dumper Symfony\Component\VarDumper\Dumper\CliDumper
- var_dumper.cloner Symfony\Component\VarDumper\Cloner\VarCloner
- web_profiler.controller.exception Symfony\Bundle\WebProfilerBundle\Controller\ExceptionController
- web_profiler.controller.profiler Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController
- web_profiler.controller.router Symfony\Bundle\WebProfilerBundle\Controller\RouterController
- web_profiler.debug_toolbar Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener