diff --git a/_includes/service_container/_my_mailer.rst.inc b/_includes/service_container/_my_mailer.rst.inc index 1933a23b390..37a20edf4a9 100644 --- a/_includes/service_container/_my_mailer.rst.inc +++ b/_includes/service_container/_my_mailer.rst.inc @@ -28,9 +28,6 @@ // app/config/services.php use AppBundle\Mailer; - use Symfony\Component\DependencyInjection\Definition; - $container->setDefinition('app.mailer', new Definition( - Mailer::class, - array('sendmail') - )); + $container->register('app.mailer', Mailer::class) + ->addArgument('sendmail'); diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst index 2139efbcc45..2ca794dcb4f 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -22,7 +22,7 @@ answer. Consider the real-world example where you want to provide a plugin system for your project. A plugin should be able to add methods, or do something before or after a method is executed, without interfering with other plugins. -This is not an easy problem to solve with single inheritance, and even if +This is not an easy problem to solve with single inheritance, and even if multiple inheritance was possible with PHP, it comes with its own drawbacks. The Symfony EventDispatcher component implements the `Mediator`_ pattern @@ -198,7 +198,6 @@ determine which instance is passed. to tag services as event listeners:: use Symfony\Component\DependencyInjection\ContainerBuilder; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; @@ -208,23 +207,19 @@ determine which instance is passed. $containerBuilder->addCompilerPass(new RegisterListenersPass()); // register the event dispatcher service - $containerBuilder->setDefinition('event_dispatcher', new Definition( - ContainerAwareEventDispatcher::class, - array(new Reference('service_container')) - )); + $containerBuilder->register('event_dispatcher', ContainerAwareEventDispatcher::class) + ->addArgument(new Reference('service_container')); // register your event listener service - $listener = new Definition(\AcmeListener::class); - $listener->addTag('kernel.event_listener', array( - 'event' => 'acme.foo.action', - 'method' => 'onFooAction', - )); - $containerBuilder->setDefinition('listener_service_id', $listener); + $containerBuilder->register('listener_service_id', \AcmeListener::class) + ->addTag('kernel.event_listener', array( + 'event' => 'acme.foo.action', + 'method' => 'onFooAction', + )); // register an event subscriber - $subscriber = new Definition(\AcmeSubscriber::class); - $subscriber->addTag('kernel.event_subscriber'); - $containerBuilder->setDefinition('subscriber_service_id', $subscriber); + $containerBuilder->register('subscriber_service_id', \AcmeSubscriber::class) + ->addTag('kernel.event_subscriber'); By default, the listeners pass assumes that the event dispatcher's service id is ``event_dispatcher``, that event listeners are tagged with the @@ -441,7 +436,7 @@ EventDispatcher Aware Events and Listeners ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``EventDispatcher`` always passes the dispatched event, the event's -name and a reference to itself to the listeners. This can lead to some advanced +name and a reference to itself to the listeners. This can lead to some advanced applications of the ``EventDispatcher`` including dispatching other events inside listeners, chaining events or even lazy loading listeners into the dispatcher object. diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index fe03309a9d6..b5d66527fa7 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -192,9 +192,9 @@ If you have this kind of time-related tests:: { $stopwatch = new Stopwatch(); - $stopwatch->start(); + $stopwatch->start('event_name'); sleep(10); - $duration = $stopwatch->stop(); + $duration = $stopwatch->stop('event_name')->getDuration(); $this->assertEquals(10, $duration); } diff --git a/console/logging.rst b/console/logging.rst index 3dadf0479ca..54f46e97833 100644 --- a/console/logging.rst +++ b/console/logging.rst @@ -107,21 +107,14 @@ First configure a listener for console exception events in the service container // app/config/services.php use AppBundle\EventListener\ConsoleExceptionListener; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definitionConsoleExceptionListener = new Definition( - ConsoleExceptionListener::class, - array(new Reference('logger')) - ); - $definitionConsoleExceptionListener->addTag( - 'kernel.event_listener', - array('event' => 'console.exception') - ); - $container->setDefinition( - 'app.listener.command_exception', - $definitionConsoleExceptionListener - ); + $container->register('app.listener.command_exception', ConsoleExceptionListener::class) + ->addArgument(new Reference('logger')) + ->addTag( + 'kernel.event_listener', + array('event' => 'console.exception') + ); Then implement the actual listener:: @@ -208,21 +201,14 @@ First configure a listener for console terminate events in the service container // app/config/services.php use AppBundle\EventListener\ErrorLoggerListener; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definitionErrorLoggerListener = new Definition( - ErrorLoggerListener::class, - array(new Reference('logger')) - ); - $definitionErrorLoggerListener->addTag( - 'kernel.event_listener', - array('event' => 'console.terminate') - ); - $container->setDefinition( - 'app.listener.command_error', - $definitionErrorLoggerListener - ); + $container->register('app.listener.command_error', ErrorLoggerListener::class) + ->addArgument(new Reference('logger')) + ->addTag( + 'kernel.event_listener', + array('event' => 'console.terminate') + ); Then implement the actual listener:: diff --git a/controller/error_pages.rst b/controller/error_pages.rst index 9801b8934cd..e42997404ab 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -296,13 +296,12 @@ In that case, you might want to override one or both of the ``showAction()`` and // app/config/services.php use AppBundle\Controller\CustomExceptionController; use Symfony\Component\DependencyInjection\Reference; - use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition(CustomExceptionController::class, array( - new Reference('twig'), - '%kernel.debug%' - )); - $container->setDefinition('app.exception_controller', $definition); + $container->register('app.exception_controller', CustomExceptionController::class) + ->setArguments(array( + new Reference('twig'), + '%kernel.debug%', + )); And then configure ``twig.exception_controller`` using the controller as services syntax (e.g. ``app.exception_controller:showAction``). diff --git a/controller/service.rst b/controller/service.rst index 0c861ed872c..54f79dbe382 100644 --- a/controller/service.rst +++ b/controller/service.rst @@ -226,13 +226,10 @@ argument: // app/config/services.php use AppBundle\Controller\HelloController; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('app.hello_controller', new Definition( - HelloController::class, - array(new Reference('templating')) - )); + $container->register('app.hello_controller', HelloController::class) + ->addArgument(new Reference('templating')); Rather than fetching the ``templating`` service from the container, you can inject *only* the exact service(s) that you need directly into the controller. diff --git a/controller/upload_file.rst b/controller/upload_file.rst index c2be4805f8a..233a2818955 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -283,13 +283,10 @@ Then, define a service for this class: // app/config/services.php use AppBundle\FileUploader; - use Symfony\Component\DependencyInjection\Definition; // ... - $container->setDefinition('app.brochure_uploader', new Definition( - FileUploader::class, - array('%brochures_directory%') - )); + $container->register('app.brochure_uploader', FileUploader::class) + ->addArgument('%brochures_directory%'); Now you're ready to use this service in the controller:: @@ -411,21 +408,17 @@ Now, register this class as a Doctrine listener: // app/config/services.php use AppBundle\EventListener\BrochureUploaderListener; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $definition = new Definition( - BrochureUploaderListener::class, - array(new Reference('brochures_directory')) - ); - $definition->addTag('doctrine.event_listener', array( - 'event' => 'prePersist', - )); - $definition->addTag('doctrine.event_listener', array( - 'event' => 'preUpdate', - )); - $container->setDefinition('app.doctrine_brochure_listener', $definition); + $container->register('app.doctrine_brochure_listener', BrochureUploaderListener::class) + ->addArgument(new Reference('brochures_directory')) + ->addTag('doctrine.event_listener', array( + 'event' => 'prePersist', + )) + ->addTag('doctrine.event_listener', array( + 'event' => 'prePersist', + )); This listener is now automatically executed when persisting a new Product entity. This way, you can remove everything related to uploading from the diff --git a/doctrine/event_listeners_subscribers.rst b/doctrine/event_listeners_subscribers.rst index 587ba9f3d28..911b3cb6b4a 100644 --- a/doctrine/event_listeners_subscribers.rst +++ b/doctrine/event_listeners_subscribers.rst @@ -84,7 +84,6 @@ managers that use this connection. use AppBundle\EventListener\SearchIndexer; use AppBundle\EventListener\SearchIndexer2; use AppBundle\EventListener\SearchIndexerSubscriber; - use Symfony\Component\DependencyInjection\Definition; $container->loadFromExtension('doctrine', array( 'dbal' => array( diff --git a/doctrine/mongodb_session_storage.rst b/doctrine/mongodb_session_storage.rst index d96777620f8..fcfecfe3dd2 100644 --- a/doctrine/mongodb_session_storage.rst +++ b/doctrine/mongodb_session_storage.rst @@ -77,7 +77,6 @@ need to change/add some parameters in the main configuration file: .. code-block:: php use Symfony\Component\DependencyInjection\Reference; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; $container->loadFromExtension('framework', array( @@ -89,20 +88,19 @@ need to change/add some parameters in the main configuration file: ), )); - $container->setDefinition('mongo_client', new Definition( - \MongoClient::class, - array( + $container->register('mongo_client', \MongoClient::class) + ->setArguments(array( // if using a username and password array('mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017'), // if not using a username and password array('mongodb://%mongodb_host%:27017'), - ) - )); + )); - $container->setDefinition('session.handler.mongo', new Definition( - MongoDbSessionHandler::class, - array(new Reference('mongo_client'), '%mongo.session.options%') - )); + $container->register('session.handler.mongo', MongoDbSessionHandler::class) + ->setArguments(array( + new Reference('mongo_client'), + '%mongo.session.options%', + )); The parameters used above should be defined somewhere in your application, often in your main parameters configuration: @@ -149,7 +147,6 @@ parameters configuration: .. code-block:: php use Symfony\Component\DependencyInjection\Reference; - use Symfony\Component\DependencyInjection\Definition; $container->setParameter('mongo.session.options', array( 'database' => 'session_db', // your MongoDB database name diff --git a/doctrine/pdo_session_storage.rst b/doctrine/pdo_session_storage.rst index 428eb5e0b99..f318d4ccda1 100644 --- a/doctrine/pdo_session_storage.rst +++ b/doctrine/pdo_session_storage.rst @@ -52,6 +52,8 @@ To use it, you just need to change some parameters in the main configuration fil // app/config/config.php + use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; + // ... $container->loadFromExtension('framework', array( // ... @@ -61,11 +63,11 @@ To use it, you just need to change some parameters in the main configuration fil ), )); - $storageDefinition = new Definition(PdoSessionHandler::class, array( - 'mysql:dbname=mydatabase', - array('db_username' => 'myuser', 'db_password' => 'mypassword') - )); - $container->setDefinition('session.handler.pdo', $storageDefinition); + $container->register('session.handler.pdo', PdoSessionHandler::class) + ->setArguments(array( + 'mysql:dbname=mydatabase', + array('db_username' => 'myuser', 'db_password' => 'mypassword'), + )); Configuring the Table and Column Names -------------------------------------- @@ -106,15 +108,14 @@ a second array argument to ``PdoSessionHandler``: // app/config/config.php - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; // ... - $storageDefinition = new Definition(PdoSessionHandler::class, array( - 'mysql:dbname=mydatabase', - array('db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword') - )); - $container->setDefinition('session.handler.pdo', $storageDefinition); + $container->register('session.handler.pdo', PdoSessionHandler::class) + ->setArguments(array( + 'mysql:dbname=mydatabase', + array('db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword'), + )); These are parameters that you must configure: diff --git a/event_dispatcher/before_after_filters.rst b/event_dispatcher/before_after_filters.rst index 08acc19ef7f..b36620bc5f8 100644 --- a/event_dispatcher/before_after_filters.rst +++ b/event_dispatcher/before_after_filters.rst @@ -173,14 +173,13 @@ your listener to be called just before any controller is executed. // app/config/services.php use AppBundle\EventListener\TokenListener; - use Symfony\Component\DependencyInjection\Definition; - $listener = new Definition(TokenListener::class, array('%tokens%')); - $listener->addTag('kernel.event_listener', array( - 'event' => 'kernel.controller', - 'method' => 'onKernelController' - )); - $container->setDefinition('app.tokens.action_listener', $listener); + $container->register('app.tokens.action_listener', TokenListener::class) + ->addArgument('%tokens%') + ->addTag('kernel.event_listener', array( + 'event' => 'kernel.controller', + 'method' => 'onKernelController', + )); With this configuration, your ``TokenListener`` ``onKernelController()`` method will be executed on each request. If the controller that is about to be executed @@ -271,18 +270,17 @@ event: // app/config/services.php use AppBundle\EventListener\TokenListener; - use Symfony\Component\DependencyInjection\Definition; - $listener = new Definition(TokenListener::class, array('%tokens%')); - $listener->addTag('kernel.event_listener', array( - 'event' => 'kernel.controller', - 'method' => 'onKernelController' - )); - $listener->addTag('kernel.event_listener', array( - 'event' => 'kernel.response', - 'method' => 'onKernelResponse' - )); - $container->setDefinition('app.tokens.action_listener', $listener); + $container->register('app.tokens.action_listener', TokenListener::class) + ->addArgument('%tokens%') + ->addTag('kernel.event_listener', array( + 'event' => 'kernel.controller', + 'method' => 'onKernelController', + )) + ->addTag('kernel.event_listener', array( + 'event' => 'kernel.response', + 'method' => 'onKernelResponse', + )); That's it! The ``TokenListener`` is now notified before every controller is executed (``onKernelController()``) and after every controller returns a response diff --git a/form/create_custom_field_type.rst b/form/create_custom_field_type.rst index 8632fae9ff7..f6ba75c4a75 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -324,15 +324,10 @@ the ``genders`` parameter value as the first argument to its to-be-created // src/AppBundle/Resources/config/services.php use AppBundle\Form\Type\GenderType; - use Symfony\Component\DependencyInjection\Definition; - - $container - ->setDefinition('app.form.type.gender', new Definition( - GenderType::class, - array('%genders%') - )) - ->addTag('form.type') - ; + + $container->register('app.form.type.gender', GenderType::class) + ->addArgument('%genders%') + ->addTag('form.type'); .. tip:: diff --git a/form/data_transformers.rst b/form/data_transformers.rst index e5c6f5bb93e..9afc2388bb3 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -455,19 +455,12 @@ it's recognized as a custom field type: // app/config/services.php use AppBundle\Form\IssueSelectorType; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $container - ->setDefinition('app.type.issue_selector', new Definition( - IssueSelectorType::class, - array( - new Reference('doctrine.orm.entity_manager'), - ) - )) - ->addTag('form.type') - ; + $container->register('app.type.issue_selector', IssueSelectorType::class) + ->addArgument(new Reference('doctrine.orm.entity_manager')) + ->addTag('form.type'); Now, whenever you need to use your special ``issue_selector`` field type, it's quite easy:: diff --git a/form/dynamic_form_modification.rst b/form/dynamic_form_modification.rst index c0dd531af28..86e2d2afb7c 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -363,12 +363,9 @@ you need to register it as a service and tag it with :ref:`form.type addTag('form.type'); - - $container->setDefinition('app.form.friend_message', $definition); + $container->register('app.form.friend_message', FriendMessageFormType::class) + ->addArgument(new Reference('security.token_storage')) + ->addTag('form.type'); In a controller that extends the :class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller` class, you can simply call:: diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index 778e57bb7f3..3fdb3257e35 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -75,7 +75,7 @@ Suppose you need to access the ``doctrine.orm.entity_manager`` service so that y can make a query. First, add this as an argument to your form class:: // src/AppBundle/Form/TaskType.php - + use Doctrine\ORM\EntityManager; // ... @@ -125,16 +125,11 @@ Next, register this as a service and tag it with ``form.type``: // src/AppBundle/Resources/config/services.php use AppBundle\Form\TaskType; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container - ->setDefinition('app.form.type.task', new Definition( - TaskType::class, - array(new Reference('doctrine.orm.entity_manager')) - )) - ->addTag('form.type') - ; + $container->register('app.form.type.task', TaskType::class) + ->addArgument(new Reference('doctrine.orm.entity_manager')) + ->addTag('form.type'); That's it! Your controller - where you create the form - doesn't need to change at all: Symfony is smart enough to load the ``TaskType`` from the container. diff --git a/profiler/matchers.rst b/profiler/matchers.rst index ee18e2524ad..b0b8dae47f3 100644 --- a/profiler/matchers.rst +++ b/profiler/matchers.rst @@ -47,7 +47,7 @@ configuration: - + @@ -134,16 +134,11 @@ won't use it directly: // app/config/services.php use AppBundle\Profiler\SuperAdminMatcher; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definition = new Definition( - SuperAdminMatcher::class, - array(new Reference('security.authorization_checker')) - ); - $definition->setPublic(false); - - $container->setDefinition('app.super_admin_matcher', $definition); + $container->register('app.super_admin_matcher', SuperAdminMatcher::class) + ->addArgument(new Reference('security.authorization_checker')) + ->setPublic(false); Once the service is registered, the only thing left to do is configure the profiler to use this service as the matcher: @@ -176,7 +171,7 @@ profiler to use this service as the matcher: - + diff --git a/reference/configuration/swiftmailer.rst b/reference/configuration/swiftmailer.rst index 330ff291499..53555680760 100644 --- a/reference/configuration/swiftmailer.rst +++ b/reference/configuration/swiftmailer.rst @@ -18,11 +18,15 @@ a mailer. It is also possible to configure several mailers (see Configuration ------------- +* `url`_ * `transport`_ * `username`_ * `password`_ * `host`_ * `port`_ +* `timeout`_ +* `source_ip`_ +* `local_domain`_ * `encryption`_ * `auth_mode`_ * `spool`_ @@ -37,6 +41,15 @@ Configuration * `disable_delivery`_ * `logging`_ +url +~~~ + +**type**: ``string`` + +The entire SwiftMailer configuration using a DSN-like URL format. + +Example: ``smtp://user:pass@host:port/?timeout=60&encryption=ssl&auth_mode=login&...`` + transport ~~~~~~~~~ @@ -46,7 +59,7 @@ The exact transport method to use to deliver emails. Valid values are: * smtp * gmail (see :doc:`/email/gmail`) -* mail +* mail (deprecated in SwiftMailer since version 5.4.5) * sendmail * null (same as setting `disable_delivery`_ to ``true``) @@ -79,6 +92,30 @@ port The port when using ``smtp`` as the transport. This defaults to 465 if encryption is ``ssl`` and 25 otherwise. +timeout +~~~~~~~ + +**type**: ``integer`` + +The timeout in seconds when using ``smtp`` as the transport. + +source_ip +~~~~~~~~~ + +**type**: ``string`` + +The source IP address when using ``smtp`` as the transport. + +local_domain +~~~~~~~~~~~~ + +**type**: ``string`` + +.. versionadded:: 2.4.0 + The ``local_domain`` option was introduced in SwiftMailerBundle 2.4.0. + +The domain name to use in ``HELO`` command. + encryption ~~~~~~~~~~ @@ -191,6 +228,13 @@ logging If true, Symfony's data collector will be activated for Swift Mailer and the information will be available in the profiler. +.. tip:: + + The following options can be set via environment variables using the + ``%env()%`` syntax: ``url``, ``transport``, ``username``, ``password``, + ``host``, ``port``, ``timeout``, ``source_ip``, ``local_domain``. + For details, see the :doc:`/configuration/external_parameters` article. + Full Default Configuration -------------------------- diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 86c523c2d76..258c1b8318d 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -729,14 +729,11 @@ channel when injecting the logger in a service. .. code-block:: php use AppBundle\Log\CustomLogger; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definition = new Definition(CustomLogger::class, array( - new Reference('logger'), - )); - $definition->addTag('monolog.logger', array('channel' => 'acme')); - $container->setDefinition('app.custom_logger', $definition); + $container->register('app.custom_logger', CustomLogger::class) + ->addArgument(new Reference('logger')) + ->addTag('monolog.logger', array('channel' => 'acme')); .. tip:: diff --git a/security.rst b/security.rst index df6b7f716dd..aa8f2e8b4aa 100644 --- a/security.rst +++ b/security.rst @@ -25,6 +25,7 @@ like :ref:`logging out ` and :doc:`encoding user passwords `. .. _security-firewalls: +.. _firewalls-authentication: 1) Initial security.yml Setup (Authentication) ---------------------------------------------- @@ -450,6 +451,7 @@ If you'd like to load your users via the Doctrine ORM, that's easy! See :doc:`/security/entity_provider` for all the details. .. _security-encoding-user-password: +.. _encoding-the-user-s-password: C) Encoding the User's Password ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/security/api_key_authentication.rst b/security/api_key_authentication.rst index ab6ff09fe58..6672c700b7c 100644 --- a/security/api_key_authentication.rst +++ b/security/api_key_authentication.rst @@ -346,14 +346,12 @@ First, register it as a service. // app/config/config.php use AppBundle\Security\ApiKeyAuthenticator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $definition = new Definition(ApiKeyAuthenticator::class); - $definition->setPublic(false); - $container->setDefinition('apikey_authenticator', $definition); + $container->register('apikey_authenticator', ApiKeyAuthenticator::class) + ->setPublic(false); Now, activate it and your custom user provider (see :doc:`/security/custom_provider`) in the ``firewalls`` section of your security configuration @@ -436,7 +434,7 @@ If you have defined ``access_control``, make sure to add a new entry: # app/config/security.yml security: # ... - + access_control: - { path: ^/api, roles: ROLE_API } @@ -737,15 +735,12 @@ service: // app/config/config.php use AppBundle\Security\ApiKeyAuthenticator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $definition = new Definition(ApiKeyAuthenticator::class, array( - new Reference('security.http_utils') - )); - $definition->setPublic(false); - $container->setDefinition('apikey_authenticator', $definition); + $container->register('apikey_authenticator', ApiKeyAuthenticator::class) + ->addArgument(new Reference('security.http_utils')) + ->setPublic(false); That's it! Have fun! diff --git a/security/custom_authentication_provider.rst b/security/custom_authentication_provider.rst index f4dbb081764..3c82ec22ee9 100644 --- a/security/custom_authentication_provider.rst +++ b/security/custom_authentication_provider.rst @@ -261,13 +261,13 @@ the ``PasswordDigest`` header value matches with the user's password. // Try to fetch the cache item from pool $cacheItem = $this->cachePool->getItem(md5($nonce)); - + // Validate that the nonce is *not* in cache // if it is, this could be a replay attack if ($cacheItem->isHit()) { throw new NonceExpiredException('Previously used nonce detected'); } - + // Store the item in cache for 5 minutes $cacheItem->set(null)->expiresAfter(300); $this->cachePool->save($cacheItem); @@ -451,22 +451,21 @@ to service ids that do not exist yet: ``wsse.security.authentication.provider`` // app/config/services.php use AppBundle\Security\Authentication\Provider\WsseProvider; use AppBundle\Security\Firewall\WsseListener; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definition = new Definition(WsseProvider::class, array( - '', // User Provider - new Reference('cache.app'), - )); - $definition->setPublic(false); - $container->setDefinition('wsse.security.authentication.provider', $definition) - - $definition = new Definition(WsseListener::class, array( - new Reference('security.token_storage'), - new Reference('security.authentication.manager'), - )); - $definition->setPublic(false); - $container->setDefinition('wsse.security.authentication.listener', $definition); + $container->register('wsse.security.authentication.provider', WsseProvider::class) + ->setArguments(array( + '', // User Provider + new Reference('cache.app'), + )) + ->setPublic(false); + + $container->register('wsse.security.authentication.listener', WsseListener::class) + ->setArguments(array( + new Reference('security.token_storage'), + new Reference('security.authentication.manager'), + )) + ->setPublic(false); Now that your services are defined, tell your security context about your factory in your bundle class: diff --git a/security/custom_password_authenticator.rst b/security/custom_password_authenticator.rst index 4eafb27e331..b6fde008eef 100644 --- a/security/custom_password_authenticator.rst +++ b/security/custom_password_authenticator.rst @@ -179,15 +179,12 @@ Now, configure your ``TimeAuthenticator`` as a service: // app/config/config.php use AppBundle\Security\TimeAuthenticator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - + // ... - $container->setDefinition('time_authenticator', new Definition( - TimeAuthenticator::class, - array(new Reference('security.password_encoder')) - )); + $container->register('time_authenticator', TimeAuthenticator::class) + ->addArgument(new Reference('security.password_encoder')); Then, activate it in the ``firewalls`` section of the security configuration using the ``simple_form`` key: diff --git a/security/custom_provider.rst b/security/custom_provider.rst index cba1d6f2374..21c467e7cba 100644 --- a/security/custom_provider.rst +++ b/security/custom_provider.rst @@ -201,7 +201,6 @@ Now you make the user provider available as a service: // app/config/services.php use AppBundle\Security\User\WebserviceUserProvider; - use Symfony\Component\DependencyInjection\Definition; $container->register('app.webservice_user_provider', WebserviceUserProvider::class); diff --git a/security/securing_services.rst b/security/securing_services.rst index 96624bd9d7b..faa6ff99708 100644 --- a/security/securing_services.rst +++ b/security/securing_services.rst @@ -96,13 +96,10 @@ Then in your service configuration, you can inject the service: // app/config/services.php use AppBundle\Newsletter\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('newsletter_manager', new Definition( - NewsletterManager::class, - array(new Reference('security.authorization_checker')) - )); + $container->register('newsletter_manager', NewsletterManager::class) + ->addArgument(new Reference('security.authorization_checker')); The injected service can then be used to perform the security check when the ``sendNewsletter()`` method is called:: @@ -180,15 +177,10 @@ the :ref:`sidebar ` below): // app/config/services.php use AppBundle\Newsletter\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $definition = new Definition( - NewsletterManager::class, - // ... - )); - $definition->addTag('security.secure_service'); - $container->setDefinition('newsletter_manager', $definition); + $container->register('newsletter_manager', NewsletterManager::class) + ->addTag('security.secure_service'); You can then achieve the same results as above using an annotation:: diff --git a/service_container.rst b/service_container.rst index dda54c1f4c8..fd14176a179 100644 --- a/service_container.rst +++ b/service_container.rst @@ -156,12 +156,9 @@ the service container *how* to instantiate it: // app/config/services.php use AppBundle\Service\MessageGenerator; - use Symfony\Component\DependencyInjection\Definition; - $container->setDefinition('app.message_generator', new Definition( - MessageGenerator::class, - array() - )); + $container->register('app.message_generator', MessageGenerator::class) + ->setArguments(array()); That's it! Your service - with the unique key ``app.message_generator`` - is now available in the container. You can use it immediately inside your controller:: @@ -259,13 +256,10 @@ Next, tell the container the service has a constructor argument: // app/config/services.php use AppBundle\Service\MessageGenerator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('app.message_generator', new Definition( - MessageGenerator::class, - array(new Reference('logger')) - )); + $container->register('app.message_generator', MessageGenerator::class) + ->addArgument(new Reference('logger')); That's it! The container now knows to pass the ``logger`` service as an argument when it instantiates the ``MessageGenerator``. This is called dependency injection. @@ -336,13 +330,13 @@ service config: // app/config/services.php use AppBundle\Service\MessageGenerator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('app.message_generator', new Definition( - MessageGenerator::class, - array(new Reference('logger'), true) - )); + $container->register('app.message_generator', MessageGenerator::class) + ->setArguments(array( + new Reference('logger'), + true, + )); You can even leverage :doc:`environments ` to control this new value in different situations. @@ -394,15 +388,15 @@ and reference it with the ``%parameter_name%`` syntax: // app/config/services.php use AppBundle\Service\MessageGenerator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->setParameter('enable_generator_logging', true); - $container->setDefinition('app.message_generator', new Definition( - MessageGenerator::class, - array(new Reference('logger'), '%enable_generator_logging%') - )); + $container->register('app.message_generator', MessageGenerator::class) + ->setArguments(array( + new Reference('logger'), + '%enable_generator_logging%', + )); Actually, once you define a parameter, it can be referenced via the ``%parameter_name%`` syntax in *any* other service configuration file - like ``config.yml``. Many parameters diff --git a/service_container/alias_private.rst b/service_container/alias_private.rst index c2a61b056b8..ef89553b76f 100644 --- a/service_container/alias_private.rst +++ b/service_container/alias_private.rst @@ -50,11 +50,9 @@ public (i.e. private): .. code-block:: php use Example\Foo; - use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition(Foo::class); - $definition->setPublic(false); - $container->setDefinition('foo', $definition); + $container->register('foo', Foo::class) + ->setPublic(false); What makes private services special is that, since the container knows that the service will never be requested from outside, it can optimize whether and how it @@ -113,11 +111,10 @@ services. .. code-block:: php use AppBundle\Mail\PhpMailer; - use Symfony\Component\DependencyInjection\Definition; - $container->setDefinition('app.phpmailer', new Definition(PhpMailer::class)); + $container->register('app.phpmailer', PhpMailer::class); - $containerBuilder->setAlias('app.mailer', 'app.phpmailer'); + $container->setAlias('app.mailer', 'app.phpmailer'); This means that when using the container directly, you can access the ``app.phpmailer`` service by asking for the ``app.mailer`` service like this:: diff --git a/service_container/calls.rst b/service_container/calls.rst index f14292c2cf5..b5c6aa00bcc 100644 --- a/service_container/calls.rst +++ b/service_container/calls.rst @@ -62,7 +62,6 @@ To configure the container to call the ``setLogger`` method, use the ``calls`` k // app/config/services.php use AppBundle\Service\MessageGenerator; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->register('app.message_generator', 'AppBundle\Service\MessageGenerator') diff --git a/service_container/configurators.rst b/service_container/configurators.rst index 6c4a3dae5cd..6777821e2a5 100644 --- a/service_container/configurators.rst +++ b/service_container/configurators.rst @@ -173,7 +173,6 @@ You can configure the service configurator using the ``configurator`` option: use AppBundle\Mail\EmailFormatterManager; use AppBundle\Mail\GreetingCardManager; use AppBundle\Mail\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... @@ -182,13 +181,11 @@ You can configure the service configurator using the ``configurator`` option: $container->register('app.newsletter_manager', NewsletterManager::class) ->addArgument(new Reference('mailer')) - ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')) - ; + ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')); $container->register('app.greeting_card_manager', GreetingCardManager::class) ->addArgument(new Reference('mailer')) - ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')) - ; + ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')); .. versionadded:: 3.2 diff --git a/service_container/definitions.rst b/service_container/definitions.rst index cb894ad3b2d..6f214843edd 100644 --- a/service_container/definitions.rst +++ b/service_container/definitions.rst @@ -31,7 +31,7 @@ There are some helpful methods for working with the service definitions:: // get the definition with the "app.user_config_manager" ID or alias $definition = $container->findDefinition('app.user_config_manager'); - // add a new "app.number_generator" definitions + // add a new "app.number_generator" definition $definition = new Definition(\AppBundle\NumberGenerator::class); $container->setDefinition('app.number_generator', $definition); diff --git a/service_container/expression_language.rst b/service_container/expression_language.rst index 1b66fd6c672..100d06b4e93 100644 --- a/service_container/expression_language.rst +++ b/service_container/expression_language.rst @@ -51,13 +51,10 @@ of the new ``mailer_configuration`` service? One way is to use an expression: // app/config/config.php use AppBundle\Mailer; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\ExpressionLanguage\Expression; - $container->setDefinition('my_mailer', new Definition( - Mailer::class, - array(new Expression('service("mailer_configuration").getMailerMethod()')) - )); + $container->register('my_mailer', Mailer::class) + ->addArgument(new Expression('service("mailer_configuration").getMailerMethod()')); To learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. @@ -99,15 +96,12 @@ via a ``container`` variable. Here's another example: .. code-block:: php use AppBundle\Mailer; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\ExpressionLanguage\Expression; - $container->setDefinition('my_mailer', new Definition( - Mailer::class, - array(new Expression( + $container->register('my_mailer', Mailer::class) + ->addArgument(new Expression( "container.hasParameter('some_param') ? parameter('some_param') : 'default_value'" - )) - )); + )); Expressions can be used in ``arguments``, ``properties``, as arguments with ``configurator`` and as arguments to ``calls`` (method calls). diff --git a/service_container/factories.rst b/service_container/factories.rst index f7b306af4d7..dbfa4cbbd2c 100644 --- a/service_container/factories.rst +++ b/service_container/factories.rst @@ -66,14 +66,11 @@ configure the service container to use the use AppBundle\Email\NewsletterManager; use AppBundle\Email\NewsletterManagerStaticFactory; - use Symfony\Component\DependencyInjection\Definition; // ... - $definition = new Definition(NewsletterManager::class); - // call the static method - $definition->setFactory(array(NewsletterManagerStaticFactory::class, 'createNewsletterManager')); - - $container->setDefinition('app.newsletter_manager', $definition); + $container->register('app.newsletter_manager', \AppBundle\NumberGenerator::class) + // call the static method + ->setFactory(array(NewsletterManagerStaticFactory::class, 'createNewsletterManager')); .. note:: @@ -134,20 +131,16 @@ Configuration of the service container then looks like this: use AppBundle\Email\NewsletterManager; use AppBundle\Email\NewsletterManagerFactory; - use Symfony\Component\DependencyInjection\Definition; // ... $container->register('app.newsletter_manager_factory', NewsletterManagerFactory::class); - $newsletterManager = new Definition(NewsletterManager::class); - - // call a method on the specified factory service - $newsletterManager->setFactory(array( - new Reference('app.newsletter_manager_factory'), - 'createNewsletterManager' - )); - - $container->setDefinition('app.newsletter_manager', $newsletterManager); + $container->register('app.newsletter_manager', NewsletterManager::class) + // call a method on the specified factory service + ->setFactory(array( + new Reference('app.newsletter_manager_factory'), + 'createNewsletterManager', + )); .. note:: @@ -212,14 +205,11 @@ method in the previous example takes the ``templating`` service as an argument: use AppBundle\Email\NewsletterManager; use Symfony\Component\DependencyInjection\Reference; - use Symfony\Component\DependencyInjection\Definition; // ... - $newsletterManager = new Definition(NewsletterManager::class, array( - new Reference('templating') - )); - $newsletterManager->setFactory(array( - new Reference('app.newsletter_manager_factory'), - 'createNewsletterManager' - )); - $container->setDefinition('app.newsletter_manager', $newsletterManager); + $container->register('app.newsletter_manager', NewsletterManager::class) + ->addArgument(new Reference('templating')) + ->setFactory(array( + new Reference('app.newsletter_manager_factory'), + 'createNewsletterManager', + )); diff --git a/service_container/import.rst b/service_container/import.rst index 28e1fc10196..75fa0722ad1 100644 --- a/service_container/import.rst +++ b/service_container/import.rst @@ -76,14 +76,11 @@ service files: // app/config/services/mailer.php use AppBundle\Mailer; - use Symfony\Component\DependencyInjection\Definition; $container->setParameter('app.mailer.transport', 'sendmail'); - $container->setDefinition('app.mailer', new Definition( - Mailer::class, - array('%app.mailer.transport%') - )); + $container->register('app.mailer', Mailer::class) + ->addArgument('%app.mailer.transport%'); The definition itself hasn't changed, only its location. To make the service container load the definitions in this resource file, use the ``imports`` key diff --git a/service_container/injection_types.rst b/service_container/injection_types.rst index 7be7c7e41bd..1cad6337089 100644 --- a/service_container/injection_types.rst +++ b/service_container/injection_types.rst @@ -67,14 +67,11 @@ service container configuration: .. code-block:: php use AppBundle\Mail\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $container->setDefinition('app.newsletter_manager', new Definition( - NewsletterManager::class, - array(new Reference('mailer')) - )); + $container->register('app.newsletter_manager', NewsletterManager::class) + ->addArgument(new Reference('mailer')); .. tip:: @@ -152,13 +149,11 @@ that accepts the dependency:: .. code-block:: php use AppBundle\Mail\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... $container->register('app.newsletter_manager', NewsletterManager::class) - ->addMethodCall('setMailer', array(new Reference('mailer'))) - ; + ->addMethodCall('setMailer', array(new Reference('mailer'))); This time the advantages are: @@ -223,13 +218,11 @@ Another possibility is just setting public fields of the class directly:: .. code-block:: php use AppBundle\Mail\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... $container->register('newsletter_manager', NewsletterManager::class) - ->setProperty('mailer', new Reference('mailer')) - ; + ->setProperty('mailer', new Reference('mailer')); There are mainly only disadvantages to using property injection, it is similar to setter injection but with these additional important problems: diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 87078694a4e..36b3798bd56 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -67,12 +67,9 @@ You can mark the service as ``lazy`` by manipulating its definition: .. code-block:: php use AppBundle\Twig\AppExtension; - use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition(AppExtension::class); - $definition->setLazy(true); - - $container->setDefinition('app.twig_extension', $definition); + $container->register('app.twig_extension', AppExtension::class) + ->setLazy(true); Once you inject the service into another service, a virtual `proxy`_ with the same signature of the class representing the service should be injected. The diff --git a/service_container/optional_dependencies.rst b/service_container/optional_dependencies.rst index a5525b5dbb1..126b70eb00c 100644 --- a/service_container/optional_dependencies.rst +++ b/service_container/optional_dependencies.rst @@ -39,21 +39,16 @@ if the service does not exist: // app/config/services.php use AppBundle\Newsletter\NewsletterManager; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerInterface; - $container->setDefinition('app.mailer', ...); + $container->register('app.mailer', ...); - $container->setDefinition('app.newsletter_manager', new Definition( - NewsletterManager::class, - array( - new Reference( - 'app.mailer', - ContainerInterface::NULL_ON_INVALID_REFERENCE - ) - ) - )); + $container->register('app.newsletter_manager', NewsletterManager::class) + ->addArgument(new Reference( + 'app.mailer', + ContainerInterface::NULL_ON_INVALID_REFERENCE + )); .. note:: diff --git a/service_container/request.rst b/service_container/request.rst index 4867ed5bbd8..aa954b4f1e6 100644 --- a/service_container/request.rst +++ b/service_container/request.rst @@ -66,14 +66,12 @@ Now, just inject the ``request_stack``, which behaves like any normal service: .. code-block:: php // src/AppBundle/Resources/config/services.php - use Symfony\Component\DependencyInjection\Definition; + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Reference; // ... - $container->setDefinition('newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager', - array(new Reference('request_stack')) - )); + $container->register('newsletter_manager', NewsletterManager::class) + ->addArgument(new Reference('request_stack')); .. tip:: diff --git a/service_container/tags.rst b/service_container/tags.rst index 75bd17607ec..951d15181c1 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -46,12 +46,10 @@ to be used for a specific purpose. Take the following example: // app/config/services.php use AppBundle\Twig\AppExtension; - use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition(AppExtension::class); - $definition->setPublic(false); - $definition->addTag('twig.extension'); - $container->setDefinition('app.twig_extension', $definition); + $container->register('app.twig_extension', AppExtension::class) + ->setPublic(false) + ->addTag('twig.extension'); The ``twig.extension`` tag is a special tag that the TwigBundle uses during configuration. By giving the service this ``twig.extension`` tag, @@ -178,15 +176,12 @@ For example, you may add the following transports as services: .. code-block:: php - use Symfony\Component\DependencyInjection\Definition; + $container->register('app.smtp_transport', '\Swift_SmtpTransport') + ->addArgument('%mailer_host%') + ->addTag('app.mail_transport'); - $definitionSmtp = new Definition('\Swift_SmtpTransport', array('%mailer_host%')); - $definitionSmtp->addTag('app.mail_transport'); - $container->setDefinition('app.smtp_transport', $definitionSmtp); - - $definitionSendmail = new Definition('\Swift_SendmailTransport'); - $definitionSendmail->addTag('app.mail_transport'); - $container->setDefinition('app.sendmail_transport', $definitionSendmail); + $container->register('app.sendmail_transport', '\Swift_SendmailTransport') + ->addTag('app.mail_transport'); Notice that each service was given a tag named ``app.mail_transport``. This is the custom tag that you'll use in your compiler pass. The compiler pass is what @@ -331,15 +326,12 @@ To answer this, change the service declaration: .. code-block:: php - use Symfony\Component\DependencyInjection\Definition; - - $definitionSmtp = new Definition('\Swift_SmtpTransport', array('%mailer_host%')); - $definitionSmtp->addTag('app.mail_transport', array('alias' => 'foo')); - $container->setDefinition('app.smtp_transport', $definitionSmtp); + $container->register('app.smtp_transport', '\Swift_SmtpTransport') + ->addArgument('%mailer_host%') + ->addTag('app.mail_transport', array('alias' => 'foo')); - $definitionSendmail = new Definition('\Swift_SendmailTransport'); - $definitionSendmail->addTag('app.mail_transport', array('alias' => 'bar')); - $container->setDefinition('app.sendmail_transport', $definitionSendmail); + $container->register('app.sendmail_transport', '\Swift_SendmailTransport') + ->addTag('app.mail_transport', array('alias' => 'bar')); Notice that you've added a generic ``alias`` key to the tag. To actually use this, update the compiler:: diff --git a/service_container/third_party.rst b/service_container/third_party.rst index 3c29a02fa96..636c16f1861 100644 --- a/service_container/third_party.rst +++ b/service_container/third_party.rst @@ -85,13 +85,11 @@ Configuring the service container is easy: // app/config/services.php use AppBundle\Newsletter\NewsletterManager; - $container->setDefinition('app.newsletter_manager', new Definition( - NewsletterManager::class, - array( + $container->register('app.newsletter_manager', NewsletterManager::class) + ->setArguments(array( new Reference('mailer'), new Reference('templating'), - ) - )); + )); The ``app.newsletter_manager`` service now has access to the core ``mailer`` and ``templating`` services. This is a common way to create services specific diff --git a/session/locale_sticky_session.rst b/session/locale_sticky_session.rst index c47909921ac..74a1fc2f757 100644 --- a/session/locale_sticky_session.rst +++ b/session/locale_sticky_session.rst @@ -84,15 +84,10 @@ Then register the listener: .. code-block:: php use AppBundle\EventListener\LocaleListener; - use Symfony\Component\DependencyInjection\Definition; - $container - ->setDefinition('app.locale_listener', new Definition( - LocaleListener::class, - array('%kernel.default_locale%') - )) - ->addTag('kernel.event_subscriber') - ; + $container->register('app.locale_listener', LocaleListener::class) + ->addArgument('%kernel.default_locale%') + ->addTag('kernel.event_subscriber'); That's it! Now celebrate by changing the user's locale and seeing that it's sticky throughout the request. Remember, to get the user's locale, always diff --git a/templating/twig_extension.rst b/templating/twig_extension.rst index 1b89b0d8e96..183302a4778 100644 --- a/templating/twig_extension.rst +++ b/templating/twig_extension.rst @@ -52,13 +52,13 @@ As an example you'll create a price filter to format a given number into price:: } .. note:: - +   Prior to Twig 1.26, your extension had to define an additional ``getName()`` method that returned a string with the extension's internal name (e.g. ``app.my_extension``). When your extension needs to be compatible with Twig - versions before 1.26, include this method which is omitted in the example + versions before 1.26, include this method which is omitted in the example above. - + .. tip:: Along with custom filters, you can also add custom `functions`_ and register @@ -96,7 +96,6 @@ Now you must let the Service Container know about your newly created Twig Extens // app/config/services.php use AppBundle\Twig\AppExtension; - use Symfony\Component\DependencyInjection\Definition; $container ->register('app.twig_extension', AppExtension::class)