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 c5f77f70d58..95f74983550 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -195,7 +195,6 @@ determine which instance is passed. a compiler pass called ``RegisterListenersPass()`` in the container builder:: 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\EventDispatcher; @@ -209,17 +208,15 @@ determine which instance is passed. $containerBuilder->register('event_dispatcher', EventDispatcher::class); // register an event listener - $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 diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index 4107c170d46..c21b2ebdd19 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -190,17 +190,18 @@ Use Case If you have this kind of time-related tests:: + use PHPUnit\Framework\TestCase; use Symfony\Component\Stopwatch\Stopwatch; - class MyTest extends \PHPUnit_Framework_TestCase + class MyTest extends TestCase { public function testSomething() { $stopwatch = new Stopwatch(); - $stopwatch->start(); + $stopwatch->start('event_name'); sleep(10); - $duration = $stopwatch->stop(); + $duration = $stopwatch->stop('event_name')->getDuration(); $this->assertEquals(10, $duration); } @@ -245,12 +246,13 @@ following listener in your PHPUnit configuration: As a result, the following is guaranteed to work and is no longer a transient test:: + use PHPUnit\Framework\TestCase; use Symfony\Component\Stopwatch\Stopwatch; /** * @group time-sensitive */ - class MyTest extends \PHPUnit_Framework_TestCase + class MyTest extends TestCase { public function testSomething() { @@ -297,9 +299,10 @@ Use Case Consider the following example that uses the ``checkMX`` option of the ``Email`` constraint to test the validity of the email domain:: + use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Email; - class MyTest extends \PHPUnit_Framework_TestCase + class MyTest extends TestCase { public function testEmail() { @@ -315,12 +318,13 @@ In order to avoid making a real network connection, add the ``@dns-sensitive`` annotation to the class and use the ``DnsMock::withMockedHosts()`` to configure the data you expect to get for the given hosts:: + use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Email; /** * @group dns-sensitive */ - class MyTest extends \PHPUnit_Framework_TestCase + class MyTest extends TestCase { public function testEmails() { 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/upload_file.rst b/controller/upload_file.rst index e91db665b16..7ffe7503d97 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 ec653ddb989..09004317079 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -323,15 +323,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 2dc98fc71db..d25be612166 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -458,19 +458,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 9de0e7fc690..d948f567217 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -362,12 +362,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'); .. versionadded:: 3.3 Prior to Symfony 3.3, you needed to define form type services as ``public``. diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index 6d14a914b6b..b792c4b67f2 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -124,16 +124,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'); .. versionadded:: 3.3 Prior to Symfony 3.3, you needed to define form type services as ``public``. 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/dic_tags.rst b/reference/dic_tags.rst index 226a7d6220b..d33d8198e1b 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 b6d8587ef01..ebc5cec983f 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 a42f02ee5d5..b84b39092ab 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:: @@ -179,15 +176,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 ea756eb7836..3f45d1fbf67 100644 --- a/service_container.rst +++ b/service_container.rst @@ -179,8 +179,8 @@ the service container *how* to instantiate it: // app/config/services.php // _defaults and loading entire directories is not possible with PHP configuration - // you need to define your servicess one-by-one - use AppBundle/Service/MessageGenerator; + // you need to define your services one-by-one + use AppBundle\Service\MessageGenerator; $container->autowire(MessageGenerator::class) ->setAutoconfigured(true) @@ -220,7 +220,7 @@ You can also fetch a service directly from the container via its "id", which wil be its class name in this case:: use AppBundle\Service\MessageGenerator; - + // accessing services like this only works if you extend Controller class ProductController extend Controller { @@ -469,7 +469,7 @@ pass here. No problem! In your configuration, you can explicitly set this argume // app/config/services.php use AppBundle\Updates\SiteUpdateManager; - + // _defaults and importing directories does not work in PHP // but registering a service explicitly does $container->autowire(SiteUpdateManager::class) @@ -801,7 +801,7 @@ from the container:: public function newAction(MessageGenerator $messageGenerator) { // type-hinting it as an argument DOES work - + // but accessing it directly from the container does NOT Work $this->container->get(MessageGenerator::class); } 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 7e1e560f1a0..417a6ae6047 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -168,15 +168,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 @@ -321,15 +318,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')); .. tip:: 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 ab734276aaa..7d5101c95ac 100644 --- a/session/locale_sticky_session.rst +++ b/session/locale_sticky_session.rst @@ -83,15 +83,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 f352da02cb6..043d6f2c40f 100644 --- a/templating/twig_extension.rst +++ b/templating/twig_extension.rst @@ -95,7 +95,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)