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/console/logging.rst b/console/logging.rst index 7acbca3e81a..552b141077e 100644 --- a/console/logging.rst +++ b/console/logging.rst @@ -110,21 +110,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:: @@ -211,21 +204,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 d2f79d04ebd..c1389b848b4 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -319,13 +319,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 2c74798b8fa..28836464cd0 100644 --- a/controller/service.rst +++ b/controller/service.rst @@ -229,13 +229,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 9a3fea1f20b..6621862ff72 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -287,13 +287,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:: @@ -415,21 +412,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 ecba8f2108c..daf0c0ada6c 100644 --- a/doctrine/pdo_session_storage.rst +++ b/doctrine/pdo_session_storage.rst @@ -58,6 +58,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( // ... @@ -67,11 +69,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 -------------------------------------- @@ -112,15 +114,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'), + )); .. versionadded:: 2.6 The ``db_lifetime_col`` was introduced in Symfony 2.6. Prior to 2.6, diff --git a/event_dispatcher/before_after_filters.rst b/event_dispatcher/before_after_filters.rst index 80bd6a495da..6827343ed5e 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 168d1998975..09da766b1b8 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -325,17 +325,12 @@ 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%') - )) + $container->register('app.form.type.gender', GenderType::class) + ->addArgument('%genders%') ->addTag('form.type', array( 'alias' => 'app_gender', - )) - ; + )); .. tip:: diff --git a/form/data_transformers.rst b/form/data_transformers.rst index c6a69fba3a9..6d39bda7abd 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -408,19 +408,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 dee5f1b9b67..7d68af38e53 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -403,12 +403,9 @@ it with :ref:`dic-tags-form-type`. use AppBundle\Form\Type\FriendMessageFormType; use Symfony\Component\DependencyInjection\Reference; - $definition = new Definition(FriendMessageFormType::class, array( - new Reference('security.token_storage') - )); - $definition->addTag('form.type', array('alias' => 'app_friend_message')); - - $container->setDefinition('app.form.friend_message', $definition); + $container->register('app.form.friend_message', FriendMessageFormType::class) + ->addArgument(new Reference('security.token_storage')) + ->addTag('form.type', array('alias' => 'app_friend_message')); If you wish to create it from within a service that has access to the form factory, you then use:: diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index f8a1145f34b..916694b4ca6 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -74,7 +74,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; // ... @@ -124,18 +124,13 @@ 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')) - )) + $container->register('app.form.type.task', TaskType::class) + ->addArgument(new Reference('doctrine.orm.entity_manager')) ->addTag('form.type', array( 'alias' => 'app_task', - )) - ; + )); That's it! Use the ``alias`` key from the tag to reference your form:: diff --git a/profiler/matchers.rst b/profiler/matchers.rst index c74f335cefd..3ba3702e956 100644 --- a/profiler/matchers.rst +++ b/profiler/matchers.rst @@ -47,7 +47,7 @@ configuration: - + @@ -139,16 +139,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); .. versionadded:: 2.6 The ``security.authorization_checker`` service was introduced in Symfony 2.6. Prior @@ -185,7 +180,7 @@ profiler to use this service as the matcher: - + diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 9d375cc35fe..574023da1d7 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -718,14 +718,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/api_key_authentication.rst b/security/api_key_authentication.rst index 33a0aab2dc4..8334b934797 100644 --- a/security/api_key_authentication.rst +++ b/security/api_key_authentication.rst @@ -333,14 +333,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 @@ -423,7 +421,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 } @@ -723,15 +721,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 68f3e2d0ca0..81800cf195f 100644 --- a/security/custom_authentication_provider.rst +++ b/security/custom_authentication_provider.rst @@ -452,22 +452,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 - '%kernel.cache_dir%/security/nonces', - )); - $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 + '%kernel.cache_dir%/security/nonces', + )) + ->setPublic(false); + + $container->setDefinition('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 2b289a23338..9dc047ee14e 100644 --- a/security/custom_password_authenticator.rst +++ b/security/custom_password_authenticator.rst @@ -173,15 +173,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 f913f918333..8defa15b960 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 fa7068589ec..60a736f1766 100644 --- a/service_container/alias_private.rst +++ b/service_container/alias_private.rst @@ -49,11 +49,9 @@ to be *not* 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, if they are only injected once, they are converted from services to inlined instantiations (e.g. ``new PrivateThing()``). @@ -111,11 +109,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 f2d16cbdcc9..4c999af6137 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')); That's it! When requesting the ``app.newsletter_manager`` or ``app.greeting_card_manager`` service, the created instance will first be 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 7a57c03bf36..cce11ebd0fb 100644 --- a/service_container/factories.rst +++ b/service_container/factories.rst @@ -71,14 +71,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:: @@ -139,20 +136,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:: @@ -217,14 +210,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 2aed445984b..a1f31f9c9c1 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -70,12 +70,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 b483d2d358e..30989ec1dee 100644 --- a/service_container/request.rst +++ b/service_container/request.rst @@ -65,14 +65,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')); .. sidebar:: Why not Inject the ``request`` Service? diff --git a/service_container/scopes.rst b/service_container/scopes.rst index c7e9871aad8..59dea939444 100644 --- a/service_container/scopes.rst +++ b/service_container/scopes.rst @@ -153,12 +153,9 @@ argument is the ``ClientConfiguration`` object: // app/config/services.php use AppBundle\Mail\Mailer; - use Symfony\Component\DependencyInjection\Definition; - $definition = $container->setDefinition('my_mailer', new Definition( - Mailer::class, - array(new Reference('client_configuration'), - ))) + $definition = $container->register('my_mailer', Mailer::class) + ->addArgument(new Reference('client_configuration')) ->setScope('client'); .. _passing-container: @@ -225,13 +222,10 @@ The service configuration for this class would look something like this: // app/config/services.php use AppBundle\Mail\Mailer; - use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('my_mailer', new Definition( - Mailer::class, - array(new Reference('service_container')) - )); + $container->register('my_mailer', Mailer::class) + ->addArgument(new Reference('service_container')); .. note:: diff --git a/service_container/tags.rst b/service_container/tags.rst index 71efe661947..555a2d8d88a 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 @@ -322,15 +317,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 24aff17340c..2ac8bbf4d6a 100644 --- a/session/locale_sticky_session.rst +++ b/session/locale_sticky_session.rst @@ -85,15 +85,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)