From cd1406f975bc836f27096c9a3a1ecbf7791172f4 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 26 Nov 2016 14:18:58 +0100 Subject: [PATCH] Use PHP 5.5's ::class notation --- .../service_container/_my_mailer.rst.inc | 3 +- best_practices/forms.rst | 3 +- bundles/extension.rst | 7 +- bundles/override.rst | 3 +- components/class_loader/class_loader.rst | 8 +- components/class_loader/psr4_class_loader.rst | 6 +- .../dependency_injection/autowiring.rst | 34 +-- components/event_dispatcher.rst | 7 +- components/form.rst | 4 +- components/security/authentication.rst | 8 +- components/security/authorization.rst | 6 +- components/serializer.rst | 9 +- console/commands_as_services.rst | 14 +- console/logging.rst | 6 +- controller/error_pages.rst | 3 +- controller/service.rst | 9 +- controller/soap_web_service.rst | 4 +- controller/upload_file.rst | 10 +- create_framework/dependency_injection.rst | 36 +-- .../http_kernel_httpkernel_class.rst | 2 +- create_framework/separation_of_concerns.rst | 2 +- create_framework/unit_testing.rst | 13 +- doctrine/custom_dql_functions.rst | 17 +- doctrine/dbal.rst | 7 +- doctrine/event_listeners_subscribers.rst | 23 +- doctrine/mapping_model_classes.rst | 38 ++-- doctrine/mongodb_session_storage.rst | 18 +- doctrine/pdo_session_storage.rst | 15 +- doctrine/registration_form.rst | 7 +- doctrine/resolve_target_entity.rst | 13 +- event_dispatcher.rst | 11 +- event_dispatcher/before_after_filters.rst | 6 +- form/create_custom_field_type.rst | 3 +- form/create_form_type_extension.rst | 13 +- form/csrf_protection.rst | 4 +- form/data_based_validation.rst | 3 +- form/data_transformers.rst | 12 +- form/dynamic_form_modification.rst | 20 +- form/embedded.rst | 3 +- form/form_collections.rst | 6 +- form/form_dependencies.rst | 13 +- form/inherit_data_option.rst | 10 +- form/type_guesser.rst | 4 +- form/unit_testing.rst | 8 +- forms.rst | 6 +- logging/formatter.rst | 5 +- logging/monolog_console.rst | 4 +- logging/processors.rst | 24 +- profiler/data_collector.rst | 12 +- profiler/matchers.rst | 3 +- reference/configuration/security.rst | 4 +- reference/constraints/Callback.rst | 13 +- reference/dic_tags.rst | 211 ++++++++++-------- .../forms/types/options/data_class.rst.inc | 3 +- routing/custom_route_loader.rst | 7 +- security/api_key_authentication.rst | 18 +- security/custom_authentication_provider.rst | 24 +- security/custom_password_authenticator.rst | 11 +- security/custom_provider.rst | 17 +- security/entity_provider.rst | 4 +- security/guard_authentication.rst | 3 +- security/impersonating_user.rst | 9 +- security/ldap.rst | 22 +- security/multiple_user_providers.rst | 4 +- security/named_encoders.rst | 4 +- security/securing_services.rst | 6 +- security/target_path.rst | 4 +- security/user_checkers.rst | 4 +- security/voters.rst | 7 +- serializer.rst | 12 +- serializer/custom_encoders.rst | 15 +- service_container.rst | 13 +- service_container/alias_private.rst | 8 +- service_container/configurators.rst | 12 +- service_container/definitions.rst | 13 +- service_container/expression_language.rst | 6 +- service_container/factories.rst | 13 +- service_container/import.rst | 3 +- service_container/injection_types.rst | 9 +- service_container/lazy_services.rst | 3 +- service_container/optional_dependencies.rst | 24 +- service_container/parameters.rst | 3 +- service_container/parent_services.rst | 12 +- service_container/scopes.rst | 16 +- service_container/service_decoration.rst | 13 +- service_container/tags.rst | 19 +- service_container/third_party.rst | 4 +- session/locale_sticky_session.rst | 7 +- session/proxy_examples.rst | 4 +- setup/bundles.rst | 4 +- templating/twig_extension.rst | 3 +- testing/database.rst | 9 +- validation/custom_constraint.rst | 8 +- 93 files changed, 652 insertions(+), 461 deletions(-) diff --git a/_includes/service_container/_my_mailer.rst.inc b/_includes/service_container/_my_mailer.rst.inc index f14c2fbe282..1933a23b390 100644 --- a/_includes/service_container/_my_mailer.rst.inc +++ b/_includes/service_container/_my_mailer.rst.inc @@ -27,9 +27,10 @@ .. code-block:: php // app/config/services.php + use AppBundle\Mailer; use Symfony\Component\DependencyInjection\Definition; $container->setDefinition('app.mailer', new Definition( - 'AppBundle\Mailer', + Mailer::class, array('sendmail') )); diff --git a/best_practices/forms.rst b/best_practices/forms.rst index ad8b678147b..cbe90da9be8 100644 --- a/best_practices/forms.rst +++ b/best_practices/forms.rst @@ -19,6 +19,7 @@ form in its own PHP class:: namespace AppBundle\Form; + use AppBundle\Entity\Post; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -42,7 +43,7 @@ form in its own PHP class:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Post' + 'data_class' => Post::class, )); } } diff --git a/bundles/extension.rst b/bundles/extension.rst index 88aefd9009a..a8b8a4c108a 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -137,14 +137,17 @@ Your bundles can also add their own classes into this file thanks to the ``addClassesToCompile()`` method. Define the classes to compile as an array of their fully qualified class names:: + use AppBundle\Manager\UserManager; + use AppBundle\Utils\Slugger; + // ... public function load(array $configs, ContainerBuilder $container) { // ... $this->addClassesToCompile(array( - 'AppBundle\\Manager\\UserManager', - 'AppBundle\\Utils\\Slugger', + UserManager::class, + Slugger::class, // ... )); } diff --git a/bundles/override.rst b/bundles/override.rst index 24b90800363..328e512ffc6 100644 --- a/bundles/override.rst +++ b/bundles/override.rst @@ -45,6 +45,7 @@ example, the implementing class for the ``original-service-id`` is changed to // src/Acme/DemoBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php namespace Acme\DemoBundle\DependencyInjection\Compiler; + use Acme\DemoBundle\YourService; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -53,7 +54,7 @@ example, the implementing class for the ``original-service-id`` is changed to public function process(ContainerBuilder $container) { $definition = $container->getDefinition('original-service-id'); - $definition->setClass('Acme\DemoBundle\YourService'); + $definition->setClass(YourService::class); } } diff --git a/components/class_loader/class_loader.rst b/components/class_loader/class_loader.rst index 7bfdb802e02..adf9b6e52b2 100644 --- a/components/class_loader/class_loader.rst +++ b/components/class_loader/class_loader.rst @@ -59,10 +59,10 @@ looked for in a location list to ease the vendoring of a sub-set of classes for large projects:: $loader->addPrefixes(array( - 'Doctrine\\Common' => __DIR__.'/vendor/doctrine/common/lib', - 'Doctrine\\DBAL\\Migrations' => __DIR__.'/vendor/doctrine/migrations/lib', - 'Doctrine\\DBAL' => __DIR__.'/vendor/doctrine/dbal/lib', - 'Doctrine' => __DIR__.'/vendor/doctrine/orm/lib', + 'Doctrine\Common' => __DIR__.'/vendor/doctrine/common/lib', + 'Doctrine\DBAL\Migrations' => __DIR__.'/vendor/doctrine/migrations/lib', + 'Doctrine\DBAL' => __DIR__.'/vendor/doctrine/dbal/lib', + 'Doctrine' => __DIR__.'/vendor/doctrine/orm/lib', )); In this example, if you try to use a class in the ``Doctrine\Common`` namespace diff --git a/components/class_loader/psr4_class_loader.rst b/components/class_loader/psr4_class_loader.rst index b593e174027..dc66614892b 100644 --- a/components/class_loader/psr4_class_loader.rst +++ b/components/class_loader/psr4_class_loader.rst @@ -38,9 +38,7 @@ The directory structure will look like this: demo.php In ``demo.php`` you are going to parse the ``config.yml`` file. To do that, you -first need to configure the ``Psr4ClassLoader``: - -.. code-block:: php +first need to configure the ``Psr4ClassLoader``:: use Symfony\Component\ClassLoader\Psr4ClassLoader; use Symfony\Component\Yaml\Yaml; @@ -48,7 +46,7 @@ first need to configure the ``Psr4ClassLoader``: require __DIR__.'/lib/ClassLoader/Psr4ClassLoader.php'; $loader = new Psr4ClassLoader(); - $loader->addPrefix('Symfony\\Component\\Yaml\\', __DIR__.'/lib/Yaml'); + $loader->addPrefix('Symfony\Component\Yaml\\', __DIR__.'/lib/Yaml'); $loader->register(); $data = Yaml::parse(file_get_contents(__DIR__.'/config.yml')); diff --git a/components/dependency_injection/autowiring.rst b/components/dependency_injection/autowiring.rst index 87dad9137ba..169bce6f1f6 100644 --- a/components/dependency_injection/autowiring.rst +++ b/components/dependency_injection/autowiring.rst @@ -76,10 +76,11 @@ service is marked as autowired: .. code-block:: php + use Acme\TwitterClient; use Symfony\Component\DependencyInjection\Definition; // ... - $definition = new Definition('Acme\TwitterClient'); + $definition = new Definition(TwitterClient::class); $definition->setAutowired(true); $container->setDefinition('twitter_client', $definition); @@ -150,9 +151,8 @@ modifying the class depending of them. To follow this best practice, constructor arguments must be typehinted with interfaces and not concrete classes. It allows to replace easily the current implementation -if necessary. It also allows to use other transformers. - -Let's introduce a ``TransformerInterface``:: +if necessary. It also allows to use other transformers. You can create a +``TransformerInterface`` containing just one method (``transform()``):: namespace Acme; @@ -164,18 +164,15 @@ Let's introduce a ``TransformerInterface``:: Then edit ``Rot13Transformer`` to make it implementing the new interface:: // ... - class Rot13Transformer implements TransformerInterface - - // ... - + { + // ... + } And update ``TwitterClient`` to depend of this new interface:: class TwitterClient { - // ... - public function __construct(TransformerInterface $transformer) { // ... @@ -215,12 +212,13 @@ subsystem isn't able to find itself the interface implementation to register: .. code-block:: php + use Acme\TwitterClient; use Symfony\Component\DependencyInjection\Definition; // ... $container->register('rot13_transformer', 'Acme\Rot13Transformer'); - $clientDefinition = new Definition('Acme\TwitterClient'); + $clientDefinition = new Definition(TwitterClient::class); $clientDefinition->setAutowired(true); $container->setDefinition('twitter_client', $clientDefinition); @@ -353,23 +351,27 @@ and a Twitter client using it: .. code-block:: php + use Acme\Rot13Transformer; + use Acme\TransformerInterface; + use Acme\TwitterClient; + use Acme\UppercaseTransformer; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; // ... - $rot13Definition = new Definition('Acme\Rot13Transformer'); - $rot13Definition->setAutowiringTypes(array('Acme\TransformerInterface')); + $rot13Definition = new Definition(Rot13Transformer::class); + $rot13Definition->setAutowiringTypes(array(TransformerInterface::class)); $container->setDefinition('rot13_transformer', $rot13Definition); - $clientDefinition = new Definition('Acme\TwitterClient'); + $clientDefinition = new Definition(TwitterClient::class); $clientDefinition->setAutowired(true); $container->setDefinition('twitter_client', $clientDefinition); - $uppercaseDefinition = new Definition('Acme\UppercaseTransformer'); + $uppercaseDefinition = new Definition(UppercaseTransformer::class); $uppercaseDefinition->setAutowired(true); $container->setDefinition('uppercase_transformer', $uppercaseDefinition); - $uppercaseClientDefinition = new Definition('Acme\TwitterClient', array( + $uppercaseClientDefinition = new Definition(TwitterClient::class, array( new Reference('uppercase_transformer'), )); $container->setDefinition('uppercase_twitter_client', $uppercaseClientDefinition); diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst index fc32129fcde..61e9a91037c 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -201,6 +201,7 @@ determine which instance is passed. use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; + use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; $containerBuilder = new ContainerBuilder(new ParameterBag()); @@ -208,12 +209,12 @@ determine which instance is passed. // register the event dispatcher service $containerBuilder->setDefinition('event_dispatcher', new Definition( - 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher', + ContainerAwareEventDispatcher::class, array(new Reference('service_container')) )); // register your event listener service - $listener = new Definition('AcmeListener'); + $listener = new Definition(\AcmeListener::class); $listener->addTag('kernel.event_listener', array( 'event' => 'foo.action', 'method' => 'onFooAction', @@ -221,7 +222,7 @@ determine which instance is passed. $containerBuilder->setDefinition('listener_service_id', $listener); // register an event subscriber - $subscriber = new Definition('AcmeSubscriber'); + $subscriber = new Definition(\AcmeSubscriber::class); $subscriber->addTag('kernel.event_subscriber'); $containerBuilder->setDefinition('subscriber_service_id', $subscriber); diff --git a/components/form.rst b/components/form.rst index ebcbb5e29cb..beefdbf58e1 100644 --- a/components/form.rst +++ b/components/form.rst @@ -660,7 +660,7 @@ option when building each field: ->add('dueDate', DateType::class, array( 'constraints' => array( new NotBlank(), - new Type('\DateTime'), + new Type(\DateTime::class), ) )) ->getForm(); @@ -679,7 +679,7 @@ option when building each field: ->add('dueDate', DateType::class, array( 'constraints' => array( new NotBlank(), - new Type('\DateTime'), + new Type(\DateTime::class), ) )) ->getForm(); diff --git a/components/security/authentication.rst b/components/security/authentication.rst index fb6fc4d32bd..bbf1ca95f7d 100644 --- a/components/security/authentication.rst +++ b/components/security/authentication.rst @@ -172,19 +172,19 @@ user. This allows you to use different encoding strategies for different types of users. The default :class:`Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactory` receives an array of encoders:: + use Acme\Entity\LegacyUser; use Symfony\Component\Security\Core\Encoder\EncoderFactory; use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; + use Symfony\Component\Security\Core\User\User; $defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000); $weakEncoder = new MessageDigestPasswordEncoder('md5', true, 1); $encoders = array( - 'Symfony\\Component\\Security\\Core\\User\\User' => $defaultEncoder, - 'Acme\\Entity\\LegacyUser' => $weakEncoder, - + User::class => $defaultEncoder, + LegacyUser::class => $weakEncoder, // ... ); - $encoderFactory = new EncoderFactory($encoders); Each encoder should implement :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface` diff --git a/components/security/authorization.rst b/components/security/authorization.rst index 39dded43bf1..6d96c94a8b1 100644 --- a/components/security/authorization.rst +++ b/components/security/authorization.rst @@ -119,9 +119,11 @@ on a "remember-me" cookie, or even authenticated anonymously? .. code-block:: php use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver; + use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; + use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; - $anonymousClass = 'Symfony\Component\Security\Core\Authentication\Token\AnonymousToken'; - $rememberMeClass = 'Symfony\Component\Security\Core\Authentication\Token\RememberMeToken'; + $anonymousClass = AnonymousToken::class; + $rememberMeClass = RememberMeToken::Class; $trustResolver = new AuthenticationTrustResolver($anonymousClass, $rememberMeClass); diff --git a/components/serializer.rst b/components/serializer.rst index b0c707b1937..12c594a4eca 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -133,6 +133,8 @@ Deserializing an Object You'll now learn how to do the exact opposite. This time, the information of the ``Person`` class would be encoded in XML format:: + use Acme\Person; + $data = << foo @@ -141,7 +143,7 @@ of the ``Person`` class would be encoded in XML format:: EOF; - $person = $serializer->deserialize($data, 'Acme\Person', 'xml'); + $person = $serializer->deserialize($data, Person::class, 'xml'); In this case, :method:`Symfony\\Component\\Serializer\\Serializer::deserialize` needs three parameters: @@ -155,7 +157,8 @@ Deserializing in an Existing Object The serializer can also be used to update an existing object:: - $person = new Acme\Person(); + // ... + $person = new Person(); $person->setName('bar'); $person->setAge(99); $person->setSportsman(true); @@ -167,7 +170,7 @@ The serializer can also be used to update an existing object:: EOF; - $serializer->deserialize($data, 'Acme\Person', 'xml', array('object_to_populate' => $person)); + $serializer->deserialize($data, Person::class, 'xml', array('object_to_populate' => $person)); // $person = Acme\Person(name: 'foo', age: '69', sportsman: true) This is a common need when working with an ORM. diff --git a/console/commands_as_services.rst b/console/commands_as_services.rst index 4f17b5b3d97..d50ff5395a8 100644 --- a/console/commands_as_services.rst +++ b/console/commands_as_services.rst @@ -52,11 +52,10 @@ with ``console.command``: .. code-block:: php // app/config/config.php + use AppBundle\Command\MyCommand; + $container - ->register( - 'app.command.my_command', - 'AppBundle\Command\MyCommand' - ) + ->register('app.command.my_command', MyCommand::class) ->addTag('console.command') ; @@ -164,13 +163,12 @@ inject the ``command.default_name`` parameter: .. code-block:: php // app/config/config.php + use AppBundle\Command\MyCommand; + $container->setParameter('command.default_name', 'Javier'); $container - ->register( - 'app.command.my_command', - 'AppBundle\Command\MyCommand', - ) + ->register('app.command.my_command', MyCommand::class) ->setArguments(array('%command.default_name%')) ->addTag('console.command') ; diff --git a/console/logging.rst b/console/logging.rst index 531ac15acc1..6579d42ba37 100644 --- a/console/logging.rst +++ b/console/logging.rst @@ -109,11 +109,12 @@ First configure a listener for console exception events in the service container .. code-block:: php // app/config/services.php + use AppBundle\EventListener\ConsoleExceptionListener; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $definitionConsoleExceptionListener = new Definition( - 'AppBundle\EventListener\ConsoleExceptionListener', + ConsoleExceptionListener::class, array(new Reference('logger')) ); $definitionConsoleExceptionListener->addTag( @@ -206,11 +207,12 @@ First configure a listener for console terminate events in the service container .. code-block:: php // app/config/services.php + use AppBundle\EventListener\ErrorLoggerListener; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $definitionErrorLoggerListener = new Definition( - 'AppBundle\EventListener\ErrorLoggerListener', + ErrorLoggerListener::class, array(new Reference('logger')) ); $definitionErrorLoggerListener->addTag( diff --git a/controller/error_pages.rst b/controller/error_pages.rst index 601f87d4550..bfda93a2677 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -294,10 +294,11 @@ In that case, you might want to override one or both of the ``showAction()`` and .. code-block:: php // app/config/services.php + use AppBundle\Controller\CustomExceptionController; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition('AppBundle\Controller\CustomExceptionController', array( + $definition = new Definition(CustomExceptionController::class, array( new Reference('twig'), '%kernel.debug%' )); diff --git a/controller/service.rst b/controller/service.rst index 546fb8f7001..33fac41bd2e 100644 --- a/controller/service.rst +++ b/controller/service.rst @@ -79,11 +79,9 @@ Then you can define it as a service as follows: .. code-block:: php // app/config/services.php - use Symfony\Component\DependencyInjection\Definition; + use AppBundle\Controller\HelloController; - $container->setDefinition('app.hello_controller', new Definition( - 'AppBundle\Controller\HelloController' - )); + $container->register('app.hello_controller', HelloController::class); Referring to the Service ------------------------ @@ -227,11 +225,12 @@ argument: .. code-block:: php // 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( - 'AppBundle\Controller\HelloController', + HelloController::class, array(new Reference('templating')) )); diff --git a/controller/soap_web_service.rst b/controller/soap_web_service.rst index 134c67fb044..7c5376e2581 100644 --- a/controller/soap_web_service.rst +++ b/controller/soap_web_service.rst @@ -77,8 +77,10 @@ a ``HelloService`` object properly: .. code-block:: php // app/config/services.php + use Acme\SoapBundle\Services\HelloService; + $container - ->register('hello_service', 'Acme\SoapBundle\Services\HelloService') + ->register('hello_service', HelloService::class) ->addArgument(new Reference('mailer')); Below is an example of a controller that is capable of handling a SOAP diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 11069621c96..8971c6f5806 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -54,6 +54,7 @@ Then, add a new ``brochure`` field to the form that manages the ``Product`` enti // src/AppBundle/Form/ProductType.php namespace AppBundle\Form; + use AppBundle\Entity\Product; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -73,7 +74,7 @@ Then, add a new ``brochure`` field to the form that manages the ``Product`` enti public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Product', + 'data_class' => Product::class, )); } } @@ -276,11 +277,12 @@ Then, define a service for this class: .. code-block:: php // app/config/services.php + use AppBundle\FileUploader; use Symfony\Component\DependencyInjection\Definition; // ... $container->setDefinition('app.brochure_uploader', new Definition( - 'AppBundle\FileUploader', + FileUploader::class, array('%brochures_directory%') )); @@ -403,11 +405,13 @@ Now, register this class as a Doctrine listener: .. code-block:: php // app/config/services.php + use AppBundle\EventListener\BrochureUploaderListener; + use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... $definition = new Definition( - 'AppBundle\EventListener\BrochureUploaderListener', + BrochureUploaderListener::class, array(new Reference('brochures_directory')) ); $definition->addTag('doctrine.event_listener', array( diff --git a/create_framework/dependency_injection.rst b/create_framework/dependency_injection.rst index e8ef15f0353..97879ad9f01 100644 --- a/create_framework/dependency_injection.rst +++ b/create_framework/dependency_injection.rst @@ -94,30 +94,35 @@ Create a new file to host the dependency injection container configuration:: // example.com/src/container.php use Symfony\Component\DependencyInjection; use Symfony\Component\DependencyInjection\Reference; + use Symfony\Component\HttpFoundation; + use Symfony\Component\HttpKernel; + use Symfony\Component\Routing; + use Symfony\Component\EventDispatcher; + use Simplex\Framework; $sc = new DependencyInjection\ContainerBuilder(); - $sc->register('context', 'Symfony\Component\Routing\RequestContext'); - $sc->register('matcher', 'Symfony\Component\Routing\Matcher\UrlMatcher') + $sc->register('context', Routing\RequestContext::class); + $sc->register('matcher', Routing\Matcher\UrlMatcher::class) ->setArguments(array($routes, new Reference('context'))) ; - $sc->register('request_stack', 'Symfony\Component\HttpFoundation\RequestStack'); - $sc->register('resolver', 'Symfony\Component\HttpKernel\Controller\ControllerResolver'); + $sc->register('request_stack', HttpFoundation\RequestStack::class); + $sc->register('resolver', HttpKernel\Controller\ControllerResolver::class); - $sc->register('listener.router', 'Symfony\Component\HttpKernel\EventListener\RouterListener') + $sc->register('listener.router', HttpKernel\EventListener\RouterListener::class) ->setArguments(array(new Reference('matcher'), new Reference('request_stack'))) ; - $sc->register('listener.response', 'Symfony\Component\HttpKernel\EventListener\ResponseListener') + $sc->register('listener.response', HttpKernel\EventListener\ResponseListener::class) ->setArguments(array('UTF-8')) ; - $sc->register('listener.exception', 'Symfony\Component\HttpKernel\EventListener\ExceptionListener') - ->setArguments(array('Calendar\\Controller\\ErrorController::exceptionAction')) + $sc->register('listener.exception', HttpKernel\EventListener\ExceptionListener::class) + ->setArguments(array('Calendar\Controller\ErrorController::exceptionAction')) ; - $sc->register('dispatcher', 'Symfony\Component\EventDispatcher\EventDispatcher') + $sc->register('dispatcher', EventDispatcher\EventDispatcher::class) ->addMethodCall('addSubscriber', array(new Reference('listener.router'))) ->addMethodCall('addSubscriber', array(new Reference('listener.response'))) ->addMethodCall('addSubscriber', array(new Reference('listener.exception'))) ; - $sc->register('framework', 'Simplex\Framework') + $sc->register('framework', Framework::class) ->setArguments(array(new Reference('dispatcher'), new Reference('resolver'))) ; @@ -177,7 +182,10 @@ framework code should be the previous simple version:: Now, here is how you can register a custom listener in the front controller:: - $sc->register('listener.string_response', 'Simplex\StringResponseListener'); + // ... + use Simplex\StringResponseListener; + + $sc->register('listener.string_response', StringResposeListener::class); $sc->getDefinition('dispatcher') ->addMethodCall('addSubscriber', array(new Reference('listener.string_response'))) ; @@ -193,7 +201,8 @@ mode or not:: These parameters can be used when defining object definitions. Let's make the charset configurable:: - $sc->register('listener.response', 'Symfony\Component\HttpKernel\EventListener\ResponseListener') + // ... + $sc->register('listener.response', HttpKernel\EventListener\ResponseListener::class) ->setArguments(array('%charset%')) ; @@ -205,7 +214,8 @@ object:: Instead of relying on the convention that the routes are defined by the ``$routes`` variables, let's use a parameter again:: - $sc->register('matcher', 'Symfony\Component\Routing\Matcher\UrlMatcher') + // ... + $sc->register('matcher', Routing\Matcher\UrlMatcher::class) ->setArguments(array('%routes%', new Reference('context'))) ; diff --git a/create_framework/http_kernel_httpkernel_class.rst b/create_framework/http_kernel_httpkernel_class.rst index 5cfee4fb6d7..871fc0e14a2 100644 --- a/create_framework/http_kernel_httpkernel_class.rst +++ b/create_framework/http_kernel_httpkernel_class.rst @@ -79,7 +79,7 @@ can take any valid controller as an exception handler, so you can create an ErrorController class instead of using a Closure:: $listener = new HttpKernel\EventListener\ExceptionListener( - 'Calendar\\Controller\\ErrorController::exceptionAction' + 'Calendar\Controller\ErrorController::exceptionAction' ); $dispatcher->addSubscriber($listener); diff --git a/create_framework/separation_of_concerns.rst b/create_framework/separation_of_concerns.rst index 9340e3b6519..ceb67ef5c4b 100644 --- a/create_framework/separation_of_concerns.rst +++ b/create_framework/separation_of_concerns.rst @@ -133,7 +133,7 @@ Don't forget to update the ``example.com/src/app.php`` file accordingly:: $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( 'year' => null, - '_controller' => 'Calendar\\Controller\\LeapYearController::indexAction', + '_controller' => 'Calendar\Controller\LeapYearController::indexAction', ))); To sum up, here is the new file layout: diff --git a/create_framework/unit_testing.rst b/create_framework/unit_testing.rst index b40aac46361..d4f40c17e78 100644 --- a/create_framework/unit_testing.rst +++ b/create_framework/unit_testing.rst @@ -74,6 +74,8 @@ We are now ready to write our first test:: use Simplex\Framework; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; + use Symfony\Component\Routing; use Symfony\Component\Routing\Exception\ResourceNotFoundException; class FrameworkTest extends \PHPUnit_Framework_TestCase @@ -89,7 +91,7 @@ We are now ready to write our first test:: private function getFrameworkForException($exception) { - $matcher = $this->createMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface'); + $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); $matcher ->expects($this->once()) ->method('match') @@ -98,9 +100,9 @@ We are now ready to write our first test:: $matcher ->expects($this->once()) ->method('getContext') - ->will($this->returnValue($this->createMock('Symfony\Component\Routing\RequestContext'))) + ->will($this->returnValue($this->createMock(Routing\RequestContext::class))) ; - $resolver = $this->createMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface'); + $resolver = $this->createMock(ControllerResolverInterface::class); return new Framework($matcher, $resolver); } @@ -141,10 +143,11 @@ Response:: use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Controller\ControllerResolver; + // ... public function testControllerResponse() { - $matcher = $this->createMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface'); + $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); $matcher ->expects($this->once()) ->method('match') @@ -159,7 +162,7 @@ Response:: $matcher ->expects($this->once()) ->method('getContext') - ->will($this->returnValue($this->createMock('Symfony\Component\Routing\RequestContext'))) + ->will($this->returnValue($this->createMock(Routing\RequestContext::class))) ; $resolver = new ControllerResolver(); diff --git a/doctrine/custom_dql_functions.rst b/doctrine/custom_dql_functions.rst index 76d9365aae8..c078f8b1f83 100644 --- a/doctrine/custom_dql_functions.rst +++ b/doctrine/custom_dql_functions.rst @@ -51,19 +51,24 @@ In Symfony, you can register your custom DQL functions as follows: .. code-block:: php // app/config/config.php + use AppBundle\DQL\StringFunction; + use AppBundle\DQL\SecondStringFunction; + use AppBundle\DQL\NumericFunction; + use AppBundle\DQL\DatetimeFunction; + $container->loadFromExtension('doctrine', array( 'orm' => array( // ... 'dql' => array( 'string_functions' => array( - 'test_string' => 'AppBundle\DQL\StringFunction', - 'second_string' => 'AppBundle\DQL\SecondStringFunction', + 'test_string' => StringFunction::class, + 'second_string' => SecondStringFunction::class, ), 'numeric_functions' => array( - 'test_numeric' => 'AppBundle\DQL\NumericFunction', + 'test_numeric' => NumericFunction::class, ), 'datetime_functions' => array( - 'test_datetime' => 'AppBundle\DQL\DatetimeFunction', + 'test_datetime' => DatetimeFunction::class, ), ), ), @@ -121,6 +126,8 @@ In Symfony, you can register your custom DQL functions as follows: .. code-block:: php // app/config/config.php + use AppBundle\DQL\DatetimeFunction; + $container->loadFromExtension('doctrine', array( 'doctrine' => array( 'orm' => array( @@ -130,7 +137,7 @@ In Symfony, you can register your custom DQL functions as follows: // place your functions here 'dql' => array( 'datetime_functions' => array( - 'test_datetime' => 'AppBundle\DQL\DatetimeFunction', + 'test_datetime' => DatetimeFunction::class, ), ), ), diff --git a/doctrine/dbal.rst b/doctrine/dbal.rst index 7e911418d7b..70e183d84c5 100644 --- a/doctrine/dbal.rst +++ b/doctrine/dbal.rst @@ -121,11 +121,14 @@ mapping types, read Doctrine's `Custom Mapping Types`_ section of their document .. code-block:: php // app/config/config.php + use AppBundle\Type\CustomFirst; + use AppBundle\Type\CustomSecond; + $container->loadFromExtension('doctrine', array( 'dbal' => array( 'types' => array( - 'custom_first' => 'AppBundle\Type\CustomFirst', - 'custom_second' => 'AppBundle\Type\CustomSecond', + 'custom_first' => CustomFirst::class, + 'custom_second' => CustomSecond::class, ), ), )); diff --git a/doctrine/event_listeners_subscribers.rst b/doctrine/event_listeners_subscribers.rst index a2026e03543..eb621b3f8f5 100644 --- a/doctrine/event_listeners_subscribers.rst +++ b/doctrine/event_listeners_subscribers.rst @@ -81,6 +81,9 @@ managers that use this connection. .. code-block:: php + use AppBundle\EventListener\SearchIndexer; + use AppBundle\EventListener\SearchIndexer2; + use AppBundle\EventListener\SearchIndexerSubscriber; use Symfony\Component\DependencyInjection\Definition; $container->loadFromExtension('doctrine', array( @@ -96,24 +99,18 @@ managers that use this connection. )); $container - ->setDefinition( - 'my.listener', - new Definition('AppBundle\EventListener\SearchIndexer') - ) + ->register('my.listener', SearchIndexer::class) ->addTag('doctrine.event_listener', array('event' => 'postPersist')) ; $container - ->setDefinition( - 'my.listener2', - new Definition('AppBundle\EventListener\SearchIndexer2') - ) - ->addTag('doctrine.event_listener', array('event' => 'postPersist', 'connection' => 'default')) + ->register('my.listener2', SearchIndexer2::class) + ->addTag('doctrine.event_listener', array( + 'event' => 'postPersist', + 'connection' => 'default' + )) ; $container - ->setDefinition( - 'my.subscriber', - new Definition('AppBundle\EventListener\SearchIndexerSubscriber') - ) + ->register('my.subscriber', SearchIndexerSubscriber::class) ->addTag('doctrine.event_subscriber', array('connection' => 'default')) ; diff --git a/doctrine/mapping_model_classes.rst b/doctrine/mapping_model_classes.rst index 6cbb748c1a6..25c9f123d5a 100644 --- a/doctrine/mapping_model_classes.rst +++ b/doctrine/mapping_model_classes.rst @@ -31,6 +31,7 @@ be adapted for your case:: use Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass; use Doctrine\Bundle\CouchDBBundle\DependencyInjection\Compiler\DoctrineCouchDBMappingsPass; use Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass; + use Symfony\Cmf\RoutingBundle\Model; class CmfRoutingBundle extends Bundle { @@ -41,50 +42,46 @@ be adapted for your case:: $modelDir = realpath(__DIR__.'/Resources/config/doctrine/model'); $mappings = array( - $modelDir => 'Symfony\Cmf\RoutingBundle\Model', + $modelDir => Model::class, ); - $ormCompilerClass = 'Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass'; - if (class_exists($ormCompilerClass)) { + if (class_exists(DoctrineOrmMappingsPass::class)) { $container->addCompilerPass( DoctrineOrmMappingsPass::createXmlMappingDriver( $mappings, array('cmf_routing.model_manager_name'), 'cmf_routing.backend_type_orm', - array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model') + array('CmfRoutingBundle' => Model::class) )); } - $mongoCompilerClass = 'Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass'; - if (class_exists($mongoCompilerClass)) { + if (class_exists(DoctrieMongoDBMappingsPass::class)) { $container->addCompilerPass( DoctrineMongoDBMappingsPass::createXmlMappingDriver( $mappings, array('cmf_routing.model_manager_name'), 'cmf_routing.backend_type_mongodb', - array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model') + array('CmfRoutingBundle' => Model::class) )); } - $couchCompilerClass = 'Doctrine\Bundle\CouchDBBundle\DependencyInjection\Compiler\DoctrineCouchDBMappingsPass'; - if (class_exists($couchCompilerClass)) { + if (class_exists(DoctrineCouchDBMappingsPass::class)) { $container->addCompilerPass( DoctrineCouchDBMappingsPass::createXmlMappingDriver( $mappings, array('cmf_routing.model_manager_name'), 'cmf_routing.backend_type_couchdb', - array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model') + array('CmfRoutingBundle' => Model::class) )); } - $phpcrCompilerClass = 'Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass'; - if (class_exists($phpcrCompilerClass)) { + if (class_exists(DoctrinePhpcrMappingsPass::class)) { $container->addCompilerPass( DoctrinePhpcrMappingsPass::createXmlMappingDriver( $mappings, array('cmf_routing.model_manager_name'), 'cmf_routing.backend_type_phpcr', - array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model') + array('CmfRoutingBundle' => Model::class) )); } } @@ -125,15 +122,22 @@ Annotations, XML, Yaml, PHP and StaticPHP. The arguments are: ``DoctrineOrmMappingsPass`` and adapted to use the ``DefaultFileLocator`` instead of the ``SymfonyFileLocator``:: + use Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator; + use Doctrine\ORM\Mapping\Driver\XmlDriver; + use AppBundle\Model; + + // ... private function buildMappingCompilerPass() { - $arguments = array(array(realpath(__DIR__ . '/Resources/config/doctrine-base')), '.orm.xml'); - $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator', $arguments); - $driver = new Definition('Doctrine\ORM\Mapping\Driver\XmlDriver', array($locator)); + $locator = new Definition(DefaultFileLocator::class, array( + array(realpath(__DIR__ . '/Resources/config/doctrine-base')), + '.orm.xml' + )); + $driver = new Definition(XmlDriver::class, array($locator)); return new DoctrineOrmMappingsPass( $driver, - array('Full\Namespace'), + array(Model::class), array('your_bundle.manager_name'), 'your_bundle.orm_enabled' ); diff --git a/doctrine/mongodb_session_storage.rst b/doctrine/mongodb_session_storage.rst index 0d5b1df2444..d96777620f8 100644 --- a/doctrine/mongodb_session_storage.rst +++ b/doctrine/mongodb_session_storage.rst @@ -78,6 +78,7 @@ need to change/add some parameters in the main configuration file: use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; $container->loadFromExtension('framework', array( 'session' => array( @@ -88,15 +89,18 @@ need to change/add some parameters in the main configuration file: ), )); - $container->setDefinition('mongo_client', new Definition('MongoClient', 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('mongo_client', new Definition( + \MongoClient::class, + 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( - 'Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler', + MongoDbSessionHandler::class, array(new Reference('mongo_client'), '%mongo.session.options%') )); diff --git a/doctrine/pdo_session_storage.rst b/doctrine/pdo_session_storage.rst index 0e2c923d5d9..65a0a533eb3 100644 --- a/doctrine/pdo_session_storage.rst +++ b/doctrine/pdo_session_storage.rst @@ -51,18 +51,17 @@ To use it, you just need to change some parameters in the main configuration fil .. code-block:: php // app/config/config.php - use Symfony\Component\DependencyInjection\Definition; - use Symfony\Component\DependencyInjection\Reference; + // ... $container->loadFromExtension('framework', array( - ..., + // ... 'session' => array( - // ..., + // ... 'handler_id' => 'session.handler.pdo', ), )); - $storageDefinition = new Definition('Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler', array( + $storageDefinition = new Definition(PdoSessionHandler::class, array( 'mysql:dbname=mydatabase', array('db_username' => 'myuser', 'db_password' => 'mypassword') )); @@ -108,9 +107,10 @@ 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('Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler', array( + $storageDefinition = new Definition(PdoSessionHandler::class, array( 'mysql:dbname=mydatabase', array('db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword') )); @@ -169,7 +169,8 @@ of your project's data, you can use the connection settings from the .. code-block:: php - $storageDefinition = new Definition('Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler', array( + // ... + $storageDefinition = new Definition(PdoSessionHandler::class, array( 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%', array('db_username' => '%database_user%', 'db_password' => '%database_password%') )); diff --git a/doctrine/registration_form.rst b/doctrine/registration_form.rst index 0fb651220f7..95b1c3b4f5b 100644 --- a/doctrine/registration_form.rst +++ b/doctrine/registration_form.rst @@ -165,6 +165,7 @@ Next, create the form for the ``User`` entity:: // src/AppBundle/Form/UserType.php namespace AppBundle\Form; + use AppBundle\Entity\User; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -191,7 +192,7 @@ Next, create the form for the ``User`` entity:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\User', + 'data_class' => User::class, )); } } @@ -287,9 +288,11 @@ encoder in the security configuration: .. code-block:: php // app/config/security.php + use AppBundle\Entity\User; + $container->loadFromExtension('security', array( 'encoders' => array( - 'AppBundle\Entity\User' => 'bcrypt', + User::class => 'bcrypt', ), )); diff --git a/doctrine/resolve_target_entity.rst b/doctrine/resolve_target_entity.rst index e5fc217a8e6..b192d2bc4ff 100644 --- a/doctrine/resolve_target_entity.rst +++ b/doctrine/resolve_target_entity.rst @@ -39,9 +39,9 @@ brevity) to explain how to set up and use the ``ResolveTargetEntityListener``. A Customer entity:: - // src/Acme/AppBundle/Entity/Customer.php + // src/AppBundle/Entity/Customer.php - namespace Acme\AppBundle\Entity; + namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Acme\CustomerBundle\Entity\Customer as BaseCustomer; @@ -118,7 +118,7 @@ about the replacement: orm: # ... resolve_target_entities: - Acme\InvoiceBundle\Model\InvoiceSubjectInterface: Acme\AppBundle\Entity\Customer + Acme\InvoiceBundle\Model\InvoiceSubjectInterface: AppBundle\Entity\Customer .. code-block:: xml @@ -132,7 +132,7 @@ about the replacement: - Acme\AppBundle\Entity\Customer + AppBundle\Entity\Customer @@ -140,11 +140,14 @@ about the replacement: .. code-block:: php // app/config/config.php + use Acme\InvoiceBundle\Model\InvoiceSubjectInterface; + use AppBundle\Entity\Customer; + $container->loadFromExtension('doctrine', array( 'orm' => array( // ... 'resolve_target_entities' => array( - 'Acme\InvoiceBundle\Model\InvoiceSubjectInterface' => 'Acme\AppBundle\Entity\Customer', + InvoiceSubjectInterface::class => Customer::class, ), ), )); diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 0cb808244df..eddf0e51e52 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -102,8 +102,10 @@ using a special "tag": .. code-block:: php // app/config/services.php + use AppBundle\EventListener\ExceptionListener; + $container - ->register('app.exception_listener', 'AppBundle\EventListener\ExceptionListener') + ->register('app.exception_listener', ExceptionListener::class) ->addTag('kernel.event_listener', array('event' => 'kernel.exception')) ; @@ -208,11 +210,10 @@ Now, you just need to register the class as a service and add the .. code-block:: php // app/config/services.php + use AppBundle\EventSubscriber\ExceptionSubscriber; + $container - ->register( - 'app.exception_subscriber', - 'AppBundle\EventSubscriber\ExceptionSubscriber' - ) + ->register('app.exception_subscriber', ExceptionSubscriber::class) ->addTag('kernel.event_subscriber') ; diff --git a/event_dispatcher/before_after_filters.rst b/event_dispatcher/before_after_filters.rst index eb171b4e9ca..c6c04184bb2 100644 --- a/event_dispatcher/before_after_filters.rst +++ b/event_dispatcher/before_after_filters.rst @@ -172,9 +172,10 @@ your listener to be called just before any controller is executed. .. code-block:: php // app/config/services.php + use AppBundle\EventListener\TokenListener; use Symfony\Component\DependencyInjection\Definition; - $listener = new Definition('AppBundle\EventListener\TokenListener', array('%tokens%')); + $listener = new Definition(TokenListener::class, array('%tokens%')); $listener->addTag('kernel.event_listener', array( 'event' => 'kernel.controller', 'method' => 'onKernelController' @@ -269,9 +270,10 @@ event: .. code-block:: php // app/config/services.php + use AppBundle\EventListener\TokenListener; use Symfony\Component\DependencyInjection\Definition; - $listener = new Definition('AppBundle\EventListener\TokenListener', array('%tokens%')); + $listener = new Definition(TokenListener::class, array('%tokens%')); $listener->addTag('kernel.event_listener', array( 'event' => 'kernel.controller', 'method' => 'onKernelController' diff --git a/form/create_custom_field_type.rst b/form/create_custom_field_type.rst index 1a6d90b2552..904f3b744af 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -331,11 +331,12 @@ the ``genders`` parameter value as the first argument to its to-be-created .. code-block:: php // src/AppBundle/Resources/config/services.php + use AppBundle\Form\Type\GenderType; use Symfony\Component\DependencyInjection\Definition; $container ->setDefinition('app.form.type.gender', new Definition( - 'AppBundle\Form\Type\GenderType', + GenderType::class, array('%genders%') )) ->addTag('form.type') diff --git a/form/create_form_type_extension.rst b/form/create_form_type_extension.rst index 850127bcf2c..953eff9bd75 100644 --- a/form/create_form_type_extension.rst +++ b/form/create_form_type_extension.rst @@ -117,12 +117,15 @@ tag: .. code-block:: php + use AppBundle\Form\Extension\ImageTypeExtension; + use Symfony\Component\Form\Extension\Core\Type\FileType; + $container - ->register( - 'app.image_type_extension', - 'AppBundle\Form\Extension\ImageTypeExtension' - ) - ->addTag('form.type_extension', array('extended_type' => 'Symfony\Component\Form\Extension\Core\Type\FileType')); + ->register('app.image_type_extension', ImageTypeExtension::class) + ->addTag('form.type_extension', array( + 'extended_type' => FileType::class + )) + ; .. versionadded:: 2.8 The ``extended_type`` option is new in Symfony 2.8. Before, the option was diff --git a/form/csrf_protection.rst b/form/csrf_protection.rst index dcb117a5dbd..ea4ffac4cf3 100644 --- a/form/csrf_protection.rst +++ b/form/csrf_protection.rst @@ -30,6 +30,8 @@ that all un-rendered fields are output. The CSRF token can be customized on a form-by-form basis. For example:: + // ... + use AppBundle\Entity\Task; use Symfony\Component\OptionsResolver\OptionsResolver; class TaskType extends AbstractType @@ -39,7 +41,7 @@ The CSRF token can be customized on a form-by-form basis. For example:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Task', + 'data_class' => Task::class, 'csrf_protection' => true, 'csrf_field_name' => '_token', // a unique key to help generate the secret token diff --git a/form/data_based_validation.rst b/form/data_based_validation.rst index 3813a92fc7f..3e31be7cd67 100644 --- a/form/data_based_validation.rst +++ b/form/data_based_validation.rst @@ -8,6 +8,7 @@ If you need some advanced logic to determine the validation groups (e.g. based on submitted data), you can set the ``validation_groups`` option to an array callback:: + use AppBundle\Entity\Client; use Symfony\Component\OptionsResolver\OptionsResolver; // ... @@ -15,7 +16,7 @@ to an array callback:: { $resolver->setDefaults(array( 'validation_groups' => array( - 'AppBundle\Entity\Client', + Client::class, 'determineValidationGroups', ), )); diff --git a/form/data_transformers.rst b/form/data_transformers.rst index 679e3447621..b22de1f17aa 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -26,6 +26,7 @@ Suppose you have a Task form with a tags ``text`` type:: // src/AppBundle/Form/TaskType.php namespace AppBundle\Form\Type; + use AppBundle\Entity\Task; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; @@ -41,7 +42,7 @@ Suppose you have a Task form with a tags ``text`` type:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Task', + 'data_class' => Task::class, )); } @@ -122,6 +123,7 @@ Start by setting up the text field like normal:: // src/AppBundle/Form/TaskType.php namespace AppBundle\Form\Type; + use AppBundle\Entity\Task; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextType; @@ -139,7 +141,7 @@ Start by setting up the text field like normal:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Task' + 'data_class' => Task::class, )); } @@ -452,18 +454,18 @@ it's recognized as a custom field type: .. code-block:: php // 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( - 'AppBundle\Form\IssueSelectorType' - ), + IssueSelectorType::class, array( new Reference('doctrine.orm.entity_manager'), ) - ) + )) ->addTag('form.type') ; diff --git a/form/dynamic_form_modification.rst b/form/dynamic_form_modification.rst index 4743630f9d4..4f380ff9a78 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -38,6 +38,7 @@ a bare form class looks like:: // src/AppBundle/Form/Type/ProductType.php namespace AppBundle\Form\Type; + use AppBundle\Entity\Product; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -53,7 +54,7 @@ a bare form class looks like:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Product' + 'data_class' => Product::class, )); } } @@ -263,11 +264,12 @@ and fill in the listener logic:: // src/AppBundle/FormType/FriendMessageFormType.php - use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; + use AppBundle\Entity\User; use Doctrine\ORM\EntityRepository; + use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; - use Symfony\Bridge\Doctrine\Form\Type\EntityType; + use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; // ... @@ -301,8 +303,8 @@ and fill in the listener logic:: $form = $event->getForm(); $formOptions = array( - 'class' => 'AppBundle\Entity\User', - 'property' => 'fullName', + 'class' => User::class, + 'property' => 'fullName', 'query_builder' => function (EntityRepository $er) use ($user) { // build a custom query // return $er->createQueryBuilder('u')->addOrderBy('fullName', 'DESC'); @@ -359,12 +361,12 @@ 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); diff --git a/form/embedded.rst b/form/embedded.rst index 4cdd7cc0ca8..164c3547e56 100644 --- a/form/embedded.rst +++ b/form/embedded.rst @@ -69,6 +69,7 @@ create a form class so that a ``Category`` object can be modified by the user:: // src/AppBundle/Form/CategoryType.php namespace AppBundle\Form; + use AppBundle\Entity\Category; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -83,7 +84,7 @@ create a form class so that a ``Category`` object can be modified by the user:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Category', + 'data_class' => Category::class, )); } } diff --git a/form/form_collections.rst b/form/form_collections.rst index 67616afeeba..e0e1de425aa 100644 --- a/form/form_collections.rst +++ b/form/form_collections.rst @@ -87,6 +87,7 @@ Then, create a form class so that a ``Tag`` object can be modified by the user:: // src/AppBundle/Form/Type/TagType.php namespace AppBundle\Form\Type; + use AppBundle\Entity\Tag; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -101,7 +102,7 @@ Then, create a form class so that a ``Tag`` object can be modified by the user:: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Tag', + 'data_class' => Tag::class, )); } } @@ -116,6 +117,7 @@ Notice that you embed a collection of ``TagType`` forms using the // src/AppBundle/Form/Type/TaskType.php namespace AppBundle\Form\Type; + use AppBundle\Entity\Task; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -135,7 +137,7 @@ Notice that you embed a collection of ``TagType`` forms using the public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Task', + 'data_class' => Task::class, )); } } diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index 7eb710850b4..cb28ccd1f14 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -124,12 +124,15 @@ Next, register this as a service and tag it with ``form.type``: .. code-block:: php // src/AppBundle/Resources/config/services.php + use AppBundle\Form\TaskType; + use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Reference; + $container - ->register( - 'app.form.type.task', - 'AppBundle\Form\TaskType' - ) - ->addArgument('@doctrine.orm.entity_manager') + ->setDefinition('app.form.type.task', new Definition( + TaskType::class, + array(new Reference('doctrine.orm.entity_manager')) + )) ->addTag('form.type') ; diff --git a/form/inherit_data_option.rst b/form/inherit_data_option.rst index f4e6fdf88d6..2b74ede1260 100644 --- a/form/inherit_data_option.rst +++ b/form/inherit_data_option.rst @@ -130,24 +130,30 @@ access the properties of the ``Customer`` instance instead. Easy, eh? Finally, make this work by adding the location form to your two original forms:: // src/AppBundle/Form/Type/CompanyType.php + use AppBundle\Entity\Company; + // ... + public function buildForm(FormBuilderInterface $builder, array $options) { // ... $builder->add('foo', LocationType::class, array( - 'data_class' => 'AppBundle\Entity\Company' + 'data_class' => Company::class, )); } .. code-block:: php // src/AppBundle/Form/Type/CustomerType.php + use AppBundle\Entity\Customer; + // ... + public function buildForm(FormBuilderInterface $builder, array $options) { // ... $builder->add('bar', LocationType::class, array( - 'data_class' => 'AppBundle\Entity\Customer' + 'data_class' => Customer::class, )); } diff --git a/form/type_guesser.rst b/form/type_guesser.rst index e28dc68123d..6cd71acf00e 100644 --- a/form/type_guesser.rst +++ b/form/type_guesser.rst @@ -213,7 +213,9 @@ creating a service and tagging it as ``form.type_guesser``: .. code-block:: php // app/config/services.php - $container->register('AppBundle\Form\TypeGuesser\PHPDocTypeGuesser') + use AppBundle\Form\TypeGuesser\PHPDocTypeGuesser; + + $container->register('app.phpdoc_type_guesser', PHPDocTypeGuesser::class) ->addTag('form.type_guesser') ; diff --git a/form/unit_testing.rst b/form/unit_testing.rst index 7e835db441b..610b13af668 100644 --- a/form/unit_testing.rst +++ b/form/unit_testing.rst @@ -122,6 +122,7 @@ make sure the ``FormRegistry`` uses the created instance:: // src/AppBundle/Tests/Form/Type/TestedTypeTests.php namespace AppBundle\Tests\Form\Type; + use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Form\PreloadedExtension; // ... @@ -132,7 +133,7 @@ make sure the ``FormRegistry`` uses the created instance:: protected function setUp() { // mock any dependencies - $this->entityManager = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')->getMock(); + $this->entityManager = $this->createMock(ObjectManager::class); parent::setUp(); } @@ -176,6 +177,7 @@ allows you to return a list of extensions to register:: // ... use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Validator\ConstraintViolationList; + use Symfony\Component\Validator\Validator\ValidatorInterface; class TestedTypeTest extends TypeTestCase { @@ -183,9 +185,7 @@ allows you to return a list of extensions to register:: protected function getExtensions() { - $this->validator = $this->createMock( - 'Symfony\Component\Validator\Validator\ValidatorInterface' - ); + $this->validator = $this->createMock(ValidatorInterface::class); $this->validator ->method('validate') ->will($this->returnValue(new ConstraintViolationList())); diff --git a/forms.rst b/forms.rst index b86e9a07358..456651fb54e 100644 --- a/forms.rst +++ b/forms.rst @@ -404,7 +404,7 @@ object. $metadata->addPropertyConstraint('dueDate', new NotBlank()); $metadata->addPropertyConstraint( 'dueDate', - new Type('\DateTime') + new Type(\DateTime::class) ); } } @@ -658,12 +658,14 @@ the choice is ultimately up to you. good idea to explicitly specify the ``data_class`` option by adding the following to your form type class:: + use AppBundle\Entity\Task; use Symfony\Component\OptionsResolver\OptionsResolver; + // ... public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( - 'data_class' => 'AppBundle\Entity\Task', + 'data_class' => Task::class, )); } diff --git a/logging/formatter.rst b/logging/formatter.rst index df0f9f2a065..bcbd3f95395 100644 --- a/logging/formatter.rst +++ b/logging/formatter.rst @@ -51,8 +51,9 @@ easily. Your formatter must implement .. code-block:: php // app/config/config.php - $container - ->register('my_formatter', 'Monolog\Formatter\JsonFormatter'); + use Monolog\Formatter\JsonFormatter; + + $container->register('my_formatter', JsonFormatter::class); $container->loadFromExtension('monolog', array( 'handlers' => array( diff --git a/logging/monolog_console.rst b/logging/monolog_console.rst index a20c9e8b732..ad8db9c1f0c 100644 --- a/logging/monolog_console.rst +++ b/logging/monolog_console.rst @@ -177,8 +177,10 @@ information): .. code-block:: php // app/config/services.php + use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter; + $container - ->register('my_formatter', 'Symfony\Bridge\Monolog\Formatter\ConsoleFormatter') + ->register('my_formatter', ConsoleFormatter::class) ->addArgument('[%%datetime%%] %%start_tag%%%%message%%%%end_tag%% (%%level_name%%) %%context%% %%extra%%\n') ; diff --git a/logging/processors.rst b/logging/processors.rst index aeae8ca477c..15022af1ea3 100644 --- a/logging/processors.rst +++ b/logging/processors.rst @@ -114,18 +114,15 @@ using a processor. .. code-block:: php // app/config/config.php + use AppBundle\SessionRequestProcessor; + use Monolog\Formatter\LineFormatter; + $container - ->register( - 'monolog.formatter.session_request', - 'Monolog\Formatter\LineFormatter' - ) + ->register('monolog.formatter.session_request', LineFormatter::class) ->addArgument('[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n'); $container - ->register( - 'monolog.processor.session_request', - 'AppBundle\SessionRequestProcessor' - ) + ->register('monolog.processor.session_request', SessionRequestProcessor::class) ->addArgument(new Reference('session')) ->addTag('monolog.processor', array('method' => 'processRecord')); @@ -189,10 +186,12 @@ the ``monolog.processor`` tag: .. code-block:: php // app/config/config.php + + // ... $container ->register( 'monolog.processor.session_request', - 'AppBundle\SessionRequestProcessor' + SessionRequestProcessor::class ) ->addArgument(new Reference('session')) ->addTag('monolog.processor', array('method' => 'processRecord', 'handler' => 'main')); @@ -240,10 +239,9 @@ the ``monolog.processor`` tag: .. code-block:: php // app/config/config.php + + // ... $container - ->register( - 'monolog.processor.session_request', - 'AppBundle\SessionRequestProcessor' - ) + ->register('monolog.processor.session_request', SessionRequestProcessor::class) ->addArgument(new Reference('session')) ->addTag('monolog.processor', array('method' => 'processRecord', 'channel' => 'main')); diff --git a/profiler/data_collector.rst b/profiler/data_collector.rst index 1a7b026d88c..6c37816a81c 100644 --- a/profiler/data_collector.rst +++ b/profiler/data_collector.rst @@ -119,8 +119,10 @@ To enable a data collector, define it as a regular service and tag it as .. code-block:: php // app/config/services.php + use AppBundle\DataCollector\RequestCollector; + $container - ->register('app.request_collector', 'AppBundle\DataCollector\RequestCollector') + ->register('app.request_collector', RequestCollector::class) ->setPublic(false) ->addTag('data_collector') ; @@ -284,8 +286,10 @@ the ``data_collector`` tag in your service configuration: .. code-block:: php // app/config/services.php + use AppBundle\DataCollector\RequestCollector; + $container - ->register('app.request_collector', 'AppBundle\DataCollector\RequestCollector') + ->register('app.request_collector', RequestCollector::class) ->setPublic(false) ->addTag('data_collector', array( 'template' => 'data_collector/template.html.twig', @@ -322,8 +326,10 @@ want your collector to be displayed before them, use a higher value: .. code-block:: php // app/config/services.php + use AppBundle\DataCollector\RequestCollector; + $container - ->register('app.request_collector', 'AppBundle\DataCollector\RequestCollector') + ->register('app.request_collector', RequestCollector::class) ->addTag('data_collector', array( 'template' => '...', 'id' => '...', diff --git a/profiler/matchers.rst b/profiler/matchers.rst index 600883cc41d..55c71ad4e76 100644 --- a/profiler/matchers.rst +++ b/profiler/matchers.rst @@ -128,11 +128,12 @@ won't use it directly: .. code-block:: php // app/config/services.php + use AppBundle\Profiler\SuperAdminMatcher; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $definition = new Definition( - 'AppBundle\Profiler\SuperAdminMatcher', + SuperAdminMatcher::class, array(new Reference('security.authorization_checker')) ); $definition->setPublic(false); diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index b8762d7d48c..e96344983eb 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -539,10 +539,12 @@ Using the BCrypt Password Encoder .. code-block:: php // app/config/security.php + use Symfony\Component\Security\Core\User\User; + $container->loadFromExtension('security', array( // ... 'encoders' => array( - 'Symfony\Component\Security\Core\User\User' => array( + User::class => array( 'algorithm' => 'bcrypt', 'cost' => 15, ), diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index 2a858f0656b..c713cefe4a9 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -165,9 +165,9 @@ External Callbacks and Closures If you want to execute a static callback method that is not located in the class of the validated object, you can configure the constraint to invoke an array callable as supported by PHP's :phpfunction:`call_user_func` function. -Suppose your validation function is ``Vendor\Package\Validator::validate()``:: +Suppose your validation function is ``Acme\Validator::validate()``:: - namespace Vendor\Package; + namespace Acme; use Symfony\Component\Validator\Context\ExecutionContextInterface; // if you're using the older 2.4 validation API, you'll need this instead @@ -193,7 +193,7 @@ You can then use the following configuration to invoke this validator: use Symfony\Component\Validator\Constraints as Assert; /** - * @Assert\Callback({"Vendor\Package\Validator", "validate"}) + * @Assert\Callback({"Acme\Validator", "validate"}) */ class Author { @@ -204,7 +204,7 @@ You can then use the following configuration to invoke this validator: # src/AppBundle/Resources/config/validation.yml AppBundle\Entity\Author: constraints: - - Callback: [Vendor\Package\Validator, validate] + - Callback: [Acme\Validator, validate] .. code-block:: xml @@ -216,7 +216,7 @@ You can then use the following configuration to invoke this validator: - Vendor\Package\Validator + Acme\Validator validate @@ -227,6 +227,7 @@ You can then use the following configuration to invoke this validator: // src/AppBundle/Entity/Author.php namespace AppBundle\Entity; + use Acme\Validator; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert; @@ -235,7 +236,7 @@ You can then use the following configuration to invoke this validator: public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addConstraint(new Assert\Callback(array( - 'Vendor\Package\Validator', + Validator::class, 'validate', ))); } diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index ffbe6790ad7..3964c68b863 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -90,8 +90,8 @@ And then register it as a tagged service: .. code-block:: yaml services: - acme.my_worker: - class: MyWorker + app.custom_assetic_worker: + class: AppBundle\Assetic\CustomWorker tags: - { name: assetic.factory_worker } @@ -103,7 +103,7 @@ And then register it as a tagged service: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -111,8 +111,10 @@ And then register it as a tagged service: .. code-block:: php + use AppBundle\Assetic\CustomWorker; + $container - ->register('acme.my_worker', 'MyWorker') + ->register('app.custom_assetic_worker', CustomWorker::class) ->addTag('assetic.factory_worker') ; @@ -149,8 +151,8 @@ Second, define a service: .. code-block:: yaml services: - acme.my_filter: - class: MyFilter + app.custom_assetic_filter: + class: AppBundle\Assetic\CustomFilter tags: - { name: assetic.filter, alias: my_filter } @@ -162,7 +164,7 @@ Second, define a service: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -170,8 +172,10 @@ Second, define a service: .. code-block:: php + use AppBundle\Assetic\CustomFilter; + $container - ->register('acme.my_filter', 'MyFilter') + ->register('app.custom_assetic_filter', CustomFilter::class) ->addTag('assetic.filter', array('alias' => 'my_filter')) ; @@ -273,11 +277,13 @@ services: .. code-block:: php - $container - ->register('app.mysql_lock', 'AppBundle\Lock\MysqlLock')->setPublic(false) - ->register('app.postgresql_lock', 'AppBundle\Lock\PostgresqlLock')->setPublic(false) - ->register('app.sqlite_lock', 'AppBundle\Lock\SqliteLock')->setPublic(false) - ; + use AppBundle\Lock\MysqlLock; + use AppBundle\Lock\PostgresqlLock; + use AppBundle\Lock\SqliteLock; + + $container->register('app.mysql_lock', MysqlLock::class)->setPublic(false); + $container->register('app.postgresql_lock', PostgresqlLock::class)->setPublic(false); + $container->register('app.sqlite_lock', SqliteLock::class)->setPublic(false); Instead of dealing with these three services, your application needs a generic ``app.lock`` service that will be an alias to one of these services, depending on @@ -325,14 +331,16 @@ the generic ``app.lock`` service can be defined as follows: .. code-block:: php - $container - ->register('app.mysql_lock', 'AppBundle\Lock\MysqlLock')->setPublic(false) - ->register('app.postgresql_lock', 'AppBundle\Lock\PostgresqlLock')->setPublic(false) - ->register('app.sqlite_lock', 'AppBundle\Lock\SqliteLock')->setPublic(false) + use AppBundle\Lock\MysqlLock; + use AppBundle\Lock\PostgresqlLock; + use AppBundle\Lock\SqliteLock; - ->register('app.lock') - ->addTag('auto_alias', array('format' => 'app.%database_type%_lock')) - ; + $container->register('app.mysql_lock', MysqlLock::class)->setPublic(false); + $container->register('app.postgresql_lock', PostgresqlLock::class)->setPublic(false); + $container->register('app.sqlite_lock', SqliteLock::class)->setPublic(false); + + $container->register('app.lock') + ->addTag('auto_alias', array('format' => 'app.%database_type%_lock')); The ``format`` option defines the expression used to construct the name of the service to alias. This expression can use any container parameter (as usual, @@ -425,8 +433,8 @@ files during the cache clearing process. In order to register your custom cache clearer, first you must create a service class:: - // src/Acme/MainBundle/Cache/MyClearer.php - namespace Acme\MainBundle\Cache; + // src/AppBundle/Cache/MyClearer.php + namespace AppBundle\Cache; use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface; @@ -447,7 +455,7 @@ Then register this class and tag it with ``kernel.cache_clearer``: services: my_cache_clearer: - class: Acme\MainBundle\Cache\MyClearer + class: AppBundle\Cache\MyClearer tags: - { name: kernel.cache_clearer } @@ -459,7 +467,7 @@ Then register this class and tag it with ``kernel.cache_clearer``: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -467,8 +475,10 @@ Then register this class and tag it with ``kernel.cache_clearer``: .. code-block:: php + use AppBundle\Cache\MyClearer; + $container - ->register('my_cache_clearer', 'Acme\MainBundle\Cache\MyClearer') + ->register('my_cache_clearer', MyClearer::class) ->addTag('kernel.cache_clearer') ; @@ -489,7 +499,7 @@ To register your own cache warmer, first create a service that implements the :class:`Symfony\\Component\\HttpKernel\\CacheWarmer\\CacheWarmerInterface` interface:: // src/Acme/MainBundle/Cache/MyCustomWarmer.php - namespace Acme\MainBundle\Cache; + namespace AppBundle\Cache; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; @@ -519,8 +529,8 @@ tag: .. code-block:: yaml services: - main.warmer.my_custom_warmer: - class: Acme\MainBundle\Cache\MyCustomWarmer + app.warmer.my_custom_warmer: + class: AppBundle\Cache\MyCustomWarmer tags: - { name: kernel.cache_warmer, priority: 0 } @@ -532,8 +542,8 @@ tag: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - @@ -542,8 +552,10 @@ tag: .. code-block:: php + use AppBundle\Cache\MyCustomWarmer; + $container - ->register('main.warmer.my_custom_warmer', 'Acme\MainBundle\Cache\MyCustomWarmer') + ->register('app.warmer.my_custom_warmer', MyCustomWarmer::class) ->addTag('kernel.cache_warmer', array('priority' => 0)) ; @@ -607,8 +619,8 @@ configuration and tag it with ``kernel.event_subscriber``: .. code-block:: yaml services: - kernel.subscriber.your_subscriber_name: - class: Fully\Qualified\Subscriber\Class\Name + app.custom_subscriber: + class: AppBundle\EventListener\CustomSubscriber tags: - { name: kernel.event_subscriber } @@ -621,8 +633,8 @@ configuration and tag it with ``kernel.event_subscriber``: + id="app.custom_subscriber" + class="AppBundle\EventListener\CustomSubscriber"> @@ -631,10 +643,12 @@ configuration and tag it with ``kernel.event_subscriber``: .. code-block:: php + use AppBundle\EventListener\CustomSubscriber; + $container ->register( - 'kernel.subscriber.your_subscriber_name', - 'Fully\Qualified\Subscriber\Class\Name' + 'app.custom_subscriber', + CustomSubscriber::class ) ->addTag('kernel.event_subscriber') ; @@ -675,8 +689,8 @@ channel when injecting the logger in a service. .. code-block:: yaml services: - my_service: - class: Fully\Qualified\Loader\Class\Name + app.custom_logger: + class: AppBundle\Log\CustomLogger arguments: ['@logger'] tags: - { name: monolog.logger, channel: acme } @@ -689,7 +703,7 @@ channel when injecting the logger in a service. xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -698,11 +712,15 @@ channel when injecting the logger in a service. .. code-block:: php - $definition = new Definition('Fully\Qualified\Loader\Class\Name', array( + 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('my_service', $definition); + $container->setDefinition('app.custom_logger', $definition); .. tip:: @@ -753,8 +771,10 @@ You can add a processor globally: .. code-block:: php + use Monolog\Processor\IntrospectionProcessor; + $container - ->register('my_service', 'Monolog\Processor\IntrospectionProcessor') + ->register('my_service', IntrospectionProcessor::class) ->addTag('monolog.processor') ; @@ -792,8 +812,10 @@ attribute: .. code-block:: php + use Monolog\Processor\IntrospectionProcessor; + $container - ->register('my_service', 'Monolog\Processor\IntrospectionProcessor') + ->register('my_service', IntrospectionProcessor::class) ->addTag('monolog.processor', array('handler' => 'firephp')) ; @@ -827,8 +849,10 @@ You can also add a processor for a specific logging channel by using the .. code-block:: php + use Monolog\Processor\IntrospectionProcessor; + $container - ->register('my_service', 'Monolog\Processor\IntrospectionProcessor') + ->register('my_service', IntrospectionProcessor::class) ->addTag('monolog.processor', array('channel' => 'security')) ; @@ -850,8 +874,8 @@ of your configuration and tag it with ``routing.loader``: .. code-block:: yaml services: - routing.loader.your_loader_name: - class: Fully\Qualified\Loader\Class\Name + app.custom_routing_loader: + class: AppBundle\Routing\CustomLoader tags: - { name: routing.loader } @@ -864,8 +888,8 @@ of your configuration and tag it with ``routing.loader``: + id="app.custom_routing_loader" + class="AppBundle\Routing\CustomLoader"> @@ -874,8 +898,10 @@ of your configuration and tag it with ``routing.loader``: .. code-block:: php + use AppBundle\Routing\CustomLoader; + $container - ->register('routing.loader.your_loader_name', 'Fully\Qualified\Loader\Class\Name') + ->register('app.custom_routing_loader', CustomLoader::class) ->addTag('routing.loader') ; @@ -989,8 +1015,8 @@ templates): .. code-block:: yaml services: - templating.helper.your_helper_name: - class: Fully\Qualified\Helper\Class\Name + app.templating_helper: + class: AppBundle\Templating\AppHelper tags: - { name: templating.helper, alias: alias_name } @@ -1003,8 +1029,8 @@ templates): + id="app.templating_helper" + class="AppBundle\Templating\AppHelper"> @@ -1013,8 +1039,10 @@ templates): .. code-block:: php + use AppBundle\Templating\AppHelper; + $container - ->register('templating.helper.your_helper_name', 'Fully\Qualified\Helper\Class\Name') + ->register('app.templating_helper', AppHelper::class) ->addTag('templating.helper', array('alias' => 'alias_name')) ; @@ -1040,8 +1068,8 @@ Now, register your loader as a service and tag it with ``translation.loader``: .. code-block:: yaml services: - main.translation.my_custom_loader: - class: Acme\MainBundle\Translation\MyCustomLoader + app.translation.my_custom_loader: + class: AppBundle\Translation\MyCustomLoader tags: - { name: translation.loader, alias: bin } @@ -1054,8 +1082,8 @@ Now, register your loader as a service and tag it with ``translation.loader``: + id="app.translation.my_custom_loader" + class="AppBundle\Translation\MyCustomLoader"> @@ -1064,10 +1092,12 @@ Now, register your loader as a service and tag it with ``translation.loader``: .. code-block:: php + use AppBundle\Translation\MyCustomLoader; + $container ->register( - 'main.translation.my_custom_loader', - 'Acme\MainBundle\Translation\MyCustomLoader' + 'app.translation.my_custom_loader', + MyCustomLoader::class ) ->addTag('translation.loader', array('alias' => 'bin')) ; @@ -1137,8 +1167,8 @@ required option: ``alias``, which defines the name of the extractor:: .. code-block:: yaml services: - acme_demo.translation.extractor.foo: - class: Acme\DemoBundle\Translation\FooExtractor + app.custom_translation_extractor: + class: App\Translation\CustomExtractor tags: - { name: translation.extractor, alias: foo } @@ -1151,8 +1181,8 @@ required option: ``alias``, which defines the name of the extractor:: + id="app.custom_translation_extractor" + class="App\Translation\CustomExtractor"> @@ -1161,10 +1191,9 @@ required option: ``alias``, which defines the name of the extractor:: .. code-block:: php - $container->register( - 'acme_demo.translation.extractor.foo', - 'Acme\DemoBundle\Translation\FooExtractor' - ) + use AppBundle\Translation\CustomExtractor; + + $container->register('app.custom_translation_extractor', CustomExtractor::class) ->addTag('translation.extractor', array('alias' => 'foo')); translation.dumper @@ -1198,8 +1227,8 @@ This is the name that's used to determine which dumper should be used. .. code-block:: yaml services: - acme_demo.translation.dumper.json: - class: Acme\DemoBundle\Translation\JsonFileDumper + app.json_translation_dumper: + class: AppBundle\Translation\JsonFileDumper tags: - { name: translation.dumper, alias: json } @@ -1212,8 +1241,8 @@ This is the name that's used to determine which dumper should be used. + id="app.json_translation_dumper" + class="AppBundle\Translation\JsonFileDumper"> @@ -1222,10 +1251,9 @@ This is the name that's used to determine which dumper should be used. .. code-block:: php - $container->register( - 'acme_demo.translation.dumper.json', - 'Acme\DemoBundle\Translation\JsonFileDumper' - ) + use AppBundle\Translation\JsonFileDumper; + + $container->register('app.json_translation_dumper', JsonFileDumper::class) ->addTag('translation.dumper', array('alias' => 'json')); .. seealso:: @@ -1248,8 +1276,8 @@ configuration and tag it with ``twig.extension``: .. code-block:: yaml services: - twig.extension.your_extension_name: - class: Fully\Qualified\Extension\Class\Name + app.twig_extension: + class: AppBundle\Twig\AppExtension tags: - { name: twig.extension } @@ -1262,8 +1290,8 @@ configuration and tag it with ``twig.extension``: + id="app.twig_extension" + class="AppBundle\Twig\AppExtension"> @@ -1272,11 +1300,10 @@ configuration and tag it with ``twig.extension``: .. code-block:: php + use AppBundle\Twig\AppExtension; + $container - ->register( - 'twig.extension.your_extension_name', - 'Fully\Qualified\Extension\Class\Name' - ) + ->register('app.twig_extension', AppExtension::class) ->addTag('twig.extension') ; @@ -1336,8 +1363,8 @@ the new loader and tag it with ``twig.loader``: .. code-block:: yaml services: - acme.demo_bundle.loader.some_twig_loader: - class: Acme\DemoBundle\Loader\SomeTwigLoader + app.custom_twig_loader: + class: AppBundle\Twig\CustomLoader tags: - { name: twig.loader, priority: 0 } @@ -1350,8 +1377,8 @@ the new loader and tag it with ``twig.loader``: + id="app.custom_twig_loader" + class="AppBundle\Twig\CustomLoader"> @@ -1360,10 +1387,12 @@ the new loader and tag it with ``twig.loader``: .. code-block:: php + use AppBundle\Twig\CustomLoader; + $container ->register( - 'acme.demo_bundle.loader.some_twig_loader', - 'Acme\DemoBundle\Loader\SomeTwigLoader' + 'app.custom_twig_loader', + CustomLoader::class ) ->addTag('twig.loader', array('priority' => 0)) ; diff --git a/reference/forms/types/options/data_class.rst.inc b/reference/forms/types/options/data_class.rst.inc index 0d81c0659e4..50e034f2276 100644 --- a/reference/forms/types/options/data_class.rst.inc +++ b/reference/forms/types/options/data_class.rst.inc @@ -8,9 +8,10 @@ form, so you can use it for any form field type which requires an object. .. code-block:: php + use AppBundle\Entity\Media; use AppBundle\Form\MediaType; // ... $builder->add('media', MediaType::class, array( - 'data_class' => 'Acme\DemoBundle\Entity\Media', + 'data_class' => Media::class, )); diff --git a/routing/custom_route_loader.rst b/routing/custom_route_loader.rst index f762c4c4203..081d7aadcfd 100644 --- a/routing/custom_route_loader.rst +++ b/routing/custom_route_loader.rst @@ -166,13 +166,10 @@ Now define a service for the ``ExtraLoader``: .. code-block:: php - use Symfony\Component\DependencyInjection\Definition; + use AppBundle\Routing\ExtraLoader; $container - ->setDefinition( - 'app.routing_loader', - new Definition('AppBundle\Routing\ExtraLoader') - ) + ->register('app.routing_loader', ExtraLoader::class) ->addTag('routing.loader') ; diff --git a/security/api_key_authentication.rst b/security/api_key_authentication.rst index 3b08dc0dc97..95e8ec6c8c5 100644 --- a/security/api_key_authentication.rst +++ b/security/api_key_authentication.rst @@ -211,7 +211,7 @@ The ``$userProvider`` might look something like this:: public function supportsClass($class) { - return 'Symfony\Component\Security\Core\User\User' === $class; + return User::class === $class; } } @@ -245,10 +245,11 @@ Now register your user provider as a service: .. code-block:: php // app/config/services.php + use AppBundle\Security\ApiKeyUserProvider; // ... $container - ->register('api_key_user_provider', 'AppBundle\Security\ApiKeyUserProvider'); + ->register('api_key_user_provider', ApiKeyUserProvider::class); .. note:: @@ -355,12 +356,13 @@ First, register it as a service. .. code-block:: php // app/config/config.php + use AppBundle\Security\ApiKeyAuthenticator; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $definition = new Definition('AppBundle\Security\ApiKeyAuthenticator'); + $definition = new Definition(ApiKeyAuthenticator::class); $definition->setPublic(false); $container->setDefinition('apikey_authenticator', $definition); @@ -744,17 +746,15 @@ service: .. code-block:: php // app/config/config.php + use AppBundle\Security\ApiKeyAuthenticator; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $definition = new Definition( - 'AppBundle\Security\ApiKeyAuthenticator', - array( - new Reference('security.http_utils') - ) - ); + $definition = new Definition(ApiKeyAuthenticator::class, array( + new Reference('security.http_utils') + )); $definition->setPublic(false); $container->setDefinition('apikey_authenticator', $definition); diff --git a/security/custom_authentication_provider.rst b/security/custom_authentication_provider.rst index c7ed37628ac..d417b564fd2 100644 --- a/security/custom_authentication_provider.rst +++ b/security/custom_authentication_provider.rst @@ -454,26 +454,22 @@ to service ids that do not exist yet: ``wsse.security.authentication.provider`` .. code-block:: php // 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( - 'AppBundle\Security\Authentication\Provider\WsseProvider', - array( - '', // User Provider - '%kernel.cache_dir%/security/nonces', - ) - ); + $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( - 'AppBundle\Security\Firewall\WsseListener', - array( - new Reference('security.token_storage'), - new Reference('security.authentication.manager'), - ) - ); + $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); diff --git a/security/custom_password_authenticator.rst b/security/custom_password_authenticator.rst index 0bb6bad22a1..7f418c8b7a0 100644 --- a/security/custom_password_authenticator.rst +++ b/security/custom_password_authenticator.rst @@ -27,8 +27,8 @@ First, create a new class that implements Eventually, this will allow you to create custom logic for authenticating the user:: - // src/Acme/HelloBundle/Security/TimeAuthenticator.php - namespace Acme\HelloBundle\Security; + // src/AppBundle/Security/TimeAuthenticator.php + namespace AppBundle\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -164,7 +164,7 @@ Now, configure your ``TimeAuthenticator`` as a service: # ... time_authenticator: - class: Acme\HelloBundle\Security\TimeAuthenticator + class: AppBundle\Security\TimeAuthenticator arguments: ["@security.password_encoder"] .. code-block:: xml @@ -179,7 +179,7 @@ Now, configure your ``TimeAuthenticator`` as a service: @@ -189,13 +189,14 @@ Now, configure your ``TimeAuthenticator`` as a service: .. code-block:: php // app/config/config.php + use AppBundle\Security\TimeAuthenticator; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... $container->setDefinition('time_authenticator', new Definition( - 'Acme\HelloBundle\Security\TimeAuthenticator', + TimeAuthenticator::class, array(new Reference('security.password_encoder')) )); diff --git a/security/custom_provider.rst b/security/custom_provider.rst index 71c9dbe4fd7..24977dd14cb 100644 --- a/security/custom_provider.rst +++ b/security/custom_provider.rst @@ -123,6 +123,7 @@ Here's an example of how this might look:: // src/AppBundle/Security/User/WebserviceUserProvider.php namespace AppBundle\Security\User; + use AppBundle\Security\User\WebserviceUser; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; @@ -162,7 +163,7 @@ Here's an example of how this might look:: public function supportsClass($class) { - return $class === 'AppBundle\Security\User\WebserviceUser'; + return WebserviceUser::class === $class; } } @@ -199,12 +200,10 @@ Now you make the user provider available as a service: .. code-block:: php // app/config/services.php + use AppBundle\Security\User\WebserviceUserProvider; use Symfony\Component\DependencyInjection\Definition; - $container->setDefinition( - 'app.webservice_user_provider', - new Definition('AppBundle\Security\User\WebserviceUserProvider') - ); + $container->register('app.webservice_user_provider', WebserviceUserProvider::class); .. tip:: @@ -302,11 +301,13 @@ users, e.g. by filling in a login form. You can do this by adding a line to the .. code-block:: php // app/config/security.php + use AppBundle\Security\User\WebserviceUser; + $container->loadFromExtension('security', array( // ... 'encoders' => array( - 'AppBundle\Security\User\WebserviceUser' => 'bcrypt', + WebserviceUser::class => 'bcrypt', ), // ... )); @@ -371,11 +372,13 @@ is compared to the hashed password returned by your ``getPassword()`` method. .. code-block:: php // app/config/security.php + use AppBundle\Security\User\WebserviceUser; + $container->loadFromExtension('security', array( // ... 'encoders' => array( - 'AppBundle\Security\User\WebserviceUser' => array( + WebserviceUser::class => array( 'algorithm' => 'bcrypt', 'cost' => 12, ), diff --git a/security/entity_provider.rst b/security/entity_provider.rst index 7e434af0116..b6c8fca14f2 100644 --- a/security/entity_provider.rst +++ b/security/entity_provider.rst @@ -255,9 +255,11 @@ the username and then check the password (more on passwords in a moment): .. code-block:: php // app/config/security.php + use AppBundle\Entity\User; + $container->loadFromExtension('security', array( 'encoders' => array( - 'AppBundle\Entity\User' => array( + User::class => array( 'algorithm' => 'bcrypt', ), ), diff --git a/security/guard_authentication.rst b/security/guard_authentication.rst index 847479c371f..c2c30f49e8a 100644 --- a/security/guard_authentication.rst +++ b/security/guard_authentication.rst @@ -261,10 +261,11 @@ To finish this, register the class as a service: .. code-block:: php // app/config/services.php + use AppBundle\Security\TokenAuthenticator; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->setDefinition('app.token_authenticator', new Definition('AppBundle\Security\TokenAuthenticator')); + $container->register('app.token_authenticator', TokenAuthenticator::class); Finally, configure your ``firewalls`` key in ``security.yml`` to use this authenticator: diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index cbd2802a3ed..40f17d001fc 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -222,9 +222,14 @@ the sticky locale: .. code-block:: php // app/config/services.php + use AppBundle\EventListener\SwitchUserListener; + $container - ->register('app.switch_user_listener', 'AppBundle\EventListener\SwitchUserListener') - ->addTag('kernel.event_listener', array('event' => 'security.switch_user', 'method' => 'onSwitchUser')) + ->register('app.switch_user_listener', SwitchUserListener::class) + ->addTag('kernel.event_listener', array( + 'event' => 'security.switch_user', + 'method' => 'onSwitchUser' + )) ; .. caution:: diff --git a/security/ldap.rst b/security/ldap.rst index 66e13686857..29b984b93d8 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -59,7 +59,7 @@ definition: # app/config/services.yml services: ldap: - class: 'Symfony\Component\Ldap\LdapClient' + class: Symfony\Component\Ldap\LdapClient arguments: - my-server # host - 389 # port @@ -89,17 +89,18 @@ definition: .. code-block:: php // app/config/services.php - $container - ->register('ldap', 'Symfony\Component\Ldap\LdapClient') - ->addArgument('my-server') - ->addArgument(389) - ->addArgument(3) - ->addArgument(false) - ->addArgument(true); + use Symfony\Component\Ldap\LdapClient; + use Symfony\Component\DependencyInjection\Definition; $container - ->register('newsletter_manager', 'NewsletterManager') - ->addMethodCall('setMailer', array(new Reference('mailer'))); + ->setDefinition('ldap', new Definition(LdapClient::class, array( + 'my-server', + 389, + 3, + false, + true, + + )); Fetching Users Using the LDAP User Provider ------------------------------------------- @@ -124,6 +125,7 @@ use the ``ldap`` user provider. search_password: password default_roles: ROLE_USER uid_key: uid + .. code-block:: xml diff --git a/security/multiple_user_providers.rst b/security/multiple_user_providers.rst index eee90d9b685..621501799ab 100644 --- a/security/multiple_user_providers.rst +++ b/security/multiple_user_providers.rst @@ -57,6 +57,8 @@ a new provider that chains the two together: .. code-block:: php // app/config/security.php + use AppBundle\Entity\User; + $container->loadFromExtension('security', array( 'providers' => array( 'chain_provider' => array( @@ -73,7 +75,7 @@ a new provider that chains the two together: ), 'user_db' => array( 'entity' => array( - 'class' => 'AppBundle\Entity\User', + 'class' => User::class, 'property' => 'username', ), ), diff --git a/security/named_encoders.rst b/security/named_encoders.rst index 0cdd0b2eb7b..adce1315a1c 100644 --- a/security/named_encoders.rst +++ b/security/named_encoders.rst @@ -38,10 +38,12 @@ to apply to all instances of a specific class: .. code-block:: php // app/config/security.php + use Symfony\Component\Security\Core\User\User; + $container->loadFromExtension('security', array( // ... 'encoders' => array( - 'Symfony\Component\Security\Core\User\User' => array( + User::class => array( 'algorithm' => 'sha512', ), ), diff --git a/security/securing_services.rst b/security/securing_services.rst index 35fdc09041c..dbfa4b358c3 100644 --- a/security/securing_services.rst +++ b/security/securing_services.rst @@ -95,11 +95,12 @@ Then in your service configuration, you can inject the service: .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->setDefinition('newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager', + NewsletterManager::class, array(new Reference('security.authorization_checker')) )); @@ -178,11 +179,12 @@ the :ref:`sidebar ` below): .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $definition = new Definition( - 'AppBundle\Newsletter\NewsletterManager', + NewsletterManager::class, // ... )); $definition->addTag('security.secure_service'); diff --git a/security/target_path.rst b/security/target_path.rst index e9da39cf9ca..f2993e91f4e 100644 --- a/security/target_path.rst +++ b/security/target_path.rst @@ -41,8 +41,10 @@ configuration file. This can be done from your main configuration file (in .. code-block:: php // app/config/services.php + use AppBundle\Security\Firewall\ExceptionListener; + // ... - $container->setParameter('security.exception_listener.class', 'AppBundle\Security\Firewall\ExceptionListener'); + $container->setParameter('security.exception_listener.class', ExceptionListener::class); Next, create your own ``ExceptionListener``:: diff --git a/security/user_checkers.rst b/security/user_checkers.rst index c5041a5ef8c..9308149ef25 100644 --- a/security/user_checkers.rst +++ b/security/user_checkers.rst @@ -91,7 +91,9 @@ other service: .. code-block:: php // app/config/services.php - $container->register('app.user_checker', 'AppBundle\Security\UserChecker'); + use AppBundle\Security\UserChecker; + + $container->register('app.user_checker', UserChecker::class); All that's left to do is add the checker to the desired firewall where the value is the service id of your user checker: diff --git a/security/voters.rst b/security/voters.rst index a8076fa426a..9035f8e2b38 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -248,9 +248,9 @@ and tag it with ``security.voter``: .. code-block:: php // app/config/services.php - use Symfony\Component\DependencyInjection\Definition; + use AppBundle\Security\PostVoter; - $container->register('app.post_voter', 'AppBundle\Security\PostVoter') + $container->register('app.post_voter', PostVoter::class) ->setPublic(false) ->addTag('security.voter') ; @@ -342,10 +342,11 @@ service: .. code-block:: php // app/config/services.php + use AppBundle\Security\PostVoter; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; - $container->register('app.post_voter', 'AppBundle\Security\PostVoter') + $container->register('app.post_voter', PostVoter::class) ->addArgument(new Reference('security.access.decision_manager')) ->setPublic(false) ->addTag('security.voter') diff --git a/serializer.rst b/serializer.rst index 17274457859..a85d8b91268 100644 --- a/serializer.rst +++ b/serializer.rst @@ -129,14 +129,12 @@ Here is an example on how to load the .. code-block:: php // app/config/services.php - use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; - $definition = new Definition( - 'Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer' - )); - $definition->setPublic(false); - $definition->addTag('serializer.normalizer'); - $container->setDefinition('get_set_method_normalizer', $definition); + $container->register('get_set_method_normalizer', GetSetMethodNormalizer::class) + ->setPublic(false); + ->addTag('serializer.normalizer') + ; .. _serializer-using-serialization-groups-annotations: diff --git a/serializer/custom_encoders.rst b/serializer/custom_encoders.rst index ccdffb3a1b3..3cb4ad47425 100644 --- a/serializer/custom_encoders.rst +++ b/serializer/custom_encoders.rst @@ -19,7 +19,7 @@ Imagine you want to serialize and deserialize Yaml. For that you'll have to create your own encoder that uses the :doc:`Yaml Component `:: - namespace AppBundle\Encoder; + namespace AppBundle\Serializer; use Symfony\Component\Serializer\Encoder\DecoderInterface; use Symfony\Component\Serializer\Encoder\EncoderInterface; @@ -61,8 +61,8 @@ to inject your custom encoder into the Serializer. # app/config/services.yml services: - app.encoder.yaml: - class: AppBundle\Encoder\YamlEncoder + app.yaml_encoder: + class: AppBundle\Serializer\YamlEncoder tags: - { name: serializer.encoder } @@ -75,7 +75,7 @@ to inject your custom encoder into the Serializer. xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -84,11 +84,10 @@ to inject your custom encoder into the Serializer. .. code-block:: php // app/config/services.php + use AppBundle\Serializer\YamlEncoder; + $container - ->register( - 'app.encoder.yaml', - 'AppBundle\Encoder\YamlEncoder' - ) + ->register('app.yaml_encoder', YamlEncoder::class) ->addTag('serializer.encoder') ; diff --git a/service_container.rst b/service_container.rst index 0066022b462..1d6801ced94 100644 --- a/service_container.rst +++ b/service_container.rst @@ -198,12 +198,13 @@ straightforward. Parameters make defining services more organized and flexible: .. code-block:: php // app/config/services.php + use AppBundle\Mailer; use Symfony\Component\DependencyInjection\Definition; $container->setParameter('app.mailer.transport', 'sendmail'); $container->setDefinition('app.mailer', new Definition( - 'AppBundle\Mailer', + Mailer::class, array('%app.mailer.transport%') )); @@ -348,13 +349,14 @@ the service container gives you a much more appealing option: .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->setDefinition('app.mailer', ...); $container->setDefinition('app.newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager', + NewsletterManager::class, array(new Reference('app.mailer')) )); @@ -436,16 +438,17 @@ Injecting the dependency by the setter method just needs a change of syntax: .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->setDefinition('app.mailer', ...); - $container->setDefinition('app.newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager' - ))->addMethodCall('setMailer', array( + $definition = new Definition(NewsletterManager::class) + $definition->addMethodCall('setMailer', array( new Reference('app.mailer'), )); + $container->setDefinition('app.newsletter_manager', $definition); .. note:: diff --git a/service_container/alias_private.rst b/service_container/alias_private.rst index fa0899e3b96..1395b8e45ac 100644 --- a/service_container/alias_private.rst +++ b/service_container/alias_private.rst @@ -48,9 +48,10 @@ to be *not* public (i.e. private): .. code-block:: php + use Example\Foo; use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition('Example\Foo'); + $definition = new Definition(Foo::class); $definition->setPublic(false); $container->setDefinition('foo', $definition); @@ -101,7 +102,7 @@ services. xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -109,9 +110,10 @@ services. .. code-block:: php + use AppBundle\Mail\PhpMailer; use Symfony\Component\DependencyInjection\Definition; - $container->setDefinition('app.phpmailer', new Definition('AppBundle\PhpMailer')); + $container->setDefinition('app.phpmailer', new Definition(PhpMailer::class)); $containerBuilder->setAlias('app.mailer', 'app.phpmailer'); diff --git a/service_container/configurators.rst b/service_container/configurators.rst index 1cb5f32bd59..dd8f7f00f31 100644 --- a/service_container/configurators.rst +++ b/service_container/configurators.rst @@ -169,19 +169,23 @@ You can configure the service configurator using the ``configurator`` option: .. code-block:: php // app/config/services.php + use AppBundle\Mail\EmailConfigurator; + use AppBundle\Mail\EmailFormatterManager; + use AppBundle\Mail\GreetingCardManager; + use AppBundle\Mail\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; // ... - $container->register('app.email_formatter_manager', 'AppBundle\Mail\EmailFormatterManager'); - $container->register('app.email_configurator', 'AppBundle\Mail\EmailConfigurator'); + $container->register('app.email_formatter_manager', EmailFormatterManager::class); + $container->register('app.email_configurator', EmailConfigurator::class); - $container->register('app.newsletter_manager', 'AppBundle\Mail\NewsletterManager') + $container->register('app.newsletter_manager', NewsletterManager::class) ->addArgument(new Reference('mailer')) ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')) ; - $container->register('app.greeting_card_manager', 'AppBundle\Mail\GreetingCardManager'); + $container->register('app.greeting_card_manager', GreetingCardManager::class); ->addArgument(new Reference('mailer')) ->setConfigurator(array(new Reference('app.email_configurator'), 'configure')) ; diff --git a/service_container/definitions.rst b/service_container/definitions.rst index cab240004f3..1bdbd734305 100644 --- a/service_container/definitions.rst +++ b/service_container/definitions.rst @@ -32,11 +32,11 @@ There are some helpful methods for working with the service definitions:: $definition = $container->findDefinition($serviceId); // add a new "app.number_generator" definitions - $definition = new Definition('AppBundle\NumberGenerator'); + $definition = new Definition(\AppBundle\NumberGenerator::class); $container->setDefinition('app.number_generator', $definition); // shortcut for the previous method - $container->register('app.number_generator', 'AppBundle\NumberGenerator'); + $container->register('app.number_generator', \AppBundle\NumberGenerator::class); Working with a Definition ------------------------- @@ -54,12 +54,14 @@ Class The first optional argument of the ``Definition`` class is the fully qualified class name of the object returned when the service is fetched from the container:: + use AppBundle\Config\UserConfigManager; + use AppBundle\Config\CustomConfigManager; use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition('AppBundle\Config\UserConfigManager'); + $definition = new Definition(UserConfigManager::class); // override the class - $definition->setClass('AppBundle\Config\CustomConfigManager'); + $definition->setClass(CustomConfigManager::class); // get the class configured for this definition $class = $definition->getClass(); @@ -71,9 +73,10 @@ The second optional argument of the ``Definition`` class is an array with the arguments passed to the constructor of the object returned when the service is fetched from the container:: + use AppBundle\Config\DoctrineConfigManager; use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition('AppBundle\Config\DoctrineConfigManager', array( + $definition = new Definition(DoctrineConfigManager::class, array( new Reference('doctrine'), // a reference to another service '%app.config_table_name%' // will be resolved to the value of a container parameter )); diff --git a/service_container/expression_language.rst b/service_container/expression_language.rst index bf6e2b1ace9..8184c8166b9 100644 --- a/service_container/expression_language.rst +++ b/service_container/expression_language.rst @@ -50,11 +50,12 @@ of the new ``mailer_configuration`` service? One way is to use an expression: .. code-block:: php // app/config/config.php + use AppBundle\Mailer; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\ExpressionLanguage\Expression; $container->setDefinition('my_mailer', new Definition( - 'AppBundle\Mailer', + Mailer::class, array(new Expression('service("mailer_configuration").getMailerMethod()')) )); @@ -97,11 +98,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( - 'AppBundle\Mailer', + Mailer::class, array(new Expression( "container.hasParameter('some_param') ? parameter('some_param') : 'default_value'" )) diff --git a/service_container/factories.rst b/service_container/factories.rst index b8f9099db21..85f03d15c7f 100644 --- a/service_container/factories.rst +++ b/service_container/factories.rst @@ -77,18 +77,20 @@ configure the service container to use the .. code-block:: php + use AppBundle\Email\NewsletterManager; + use AppBundle\Email\NewsletterManagerFactory; use Symfony\Component\DependencyInjection\Definition; // ... - $definition = new Definition('AppBundle\Email\NewsletterManager'); + $definition = new Definition(NewsletterManager::class); // call a static method - $definition->setFactory(array('AppBundle\Email\NewsletterManager', 'create')); + $definition->setFactory(array(NewsletterManager::class, 'create')); $container->setDefinition('app.newsletter_manager', $definition); - $container->register('app.newsletter_manager_factory', 'AppBundle\Email\NewsletterManagerFactory'); + $container->register('app.newsletter_manager_factory', NewsletterManagerFactory::class); - $newsletterManager = new Definition('AppBundle\Email\NewsletterManager'); + $newsletterManager = new Definition(NewsletterManager::class); // call a method on the specified service $newsletterManager->setFactory(array( @@ -144,11 +146,12 @@ method in the previous example takes the ``templating`` service as an argument: .. code-block:: php + use AppBundle\Email\NewsletterManager; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; // ... - $newsletterManager = new Definition('AppBundle\Email\NewsletterManager', array( + $newsletterManager = new Definition(NewsletterManager::class, array( new Reference('templating') )); $newsletterManager->setFactory(array( diff --git a/service_container/import.rst b/service_container/import.rst index f556ace0d84..9f5bdc9f59e 100644 --- a/service_container/import.rst +++ b/service_container/import.rst @@ -75,12 +75,13 @@ service files: .. code-block:: php // 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( - 'AppBundle\Mailer', + Mailer::class, array('%app.mailer.transport%') )); diff --git a/service_container/injection_types.rst b/service_container/injection_types.rst index c5540769b40..7be7c7e41bd 100644 --- a/service_container/injection_types.rst +++ b/service_container/injection_types.rst @@ -66,12 +66,13 @@ 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( - 'AppBundle\Mail\NewsletterManager', + NewsletterManager::class, array(new Reference('mailer')) )); @@ -150,11 +151,12 @@ 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', 'AppBundle\Mail\NewsletterManager') + $container->register('app.newsletter_manager', NewsletterManager::class) ->addMethodCall('setMailer', array(new Reference('mailer'))) ; @@ -220,11 +222,12 @@ 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', 'AppBundle\Mail\NewsletterManager') + $container->register('newsletter_manager', NewsletterManager::class) ->setProperty('mailer', new Reference('mailer')) ; diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 431da97852b..2aed445984b 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -69,9 +69,10 @@ 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('AppBundle\Twig\AppExtension'); + $definition = new Definition(AppExtension::class); $definition->setLazy(true); $container->setDefinition('app.twig_extension', $definition); diff --git a/service_container/optional_dependencies.rst b/service_container/optional_dependencies.rst index 95fa9d177b3..5bc9e9b2ec3 100644 --- a/service_container/optional_dependencies.rst +++ b/service_container/optional_dependencies.rst @@ -38,6 +38,7 @@ if the service does not exist: .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -45,7 +46,7 @@ if the service does not exist: $container->setDefinition('app.mailer', ...); $container->setDefinition('app.newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager', + NewsletterManager::class, array( new Reference( 'app.mailer', @@ -104,20 +105,21 @@ call if the service exists and remove the method call if it does not: .. code-block:: php // app/config/services.php - use Symfony\Component\DependencyInjection\Definition; + use AppBundle\Newsletter\NewsletterManager; 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( - 'AppBundle\Newsletter\NewsletterManager' - ))->addMethodCall('setMailer', array( - new Reference( - 'my_mailer', - ContainerInterface::IGNORE_ON_INVALID_REFERENCE - ), - )); + $container + ->register('app.newsletter_manager', NewsletterManager::class) + ->addMethodCall('setMailer', array( + new Reference( + 'my_mailer', + ContainerInterface::IGNORE_ON_INVALID_REFERENCE + ), + )) + ; In YAML, the special ``@?`` syntax tells the service container that the dependency is optional. Of course, the ``NewsletterManager`` must also be rewritten by diff --git a/service_container/parameters.rst b/service_container/parameters.rst index 079c5c22bf9..0c1890e3dfd 100644 --- a/service_container/parameters.rst +++ b/service_container/parameters.rst @@ -77,11 +77,12 @@ and hidden with the service definition: .. code-block:: php + use AppBundle\Mailer; use Symfony\Component\DependencyInjection\Reference; $container->setParameter('mailer.transport', 'sendmail'); - $container->register('app.mailer', 'AppBundle\Mailer') + $container->register('app.mailer', Mailer::class) ->addArgument('%mailer.transport%'); .. caution:: diff --git a/service_container/parent_services.rst b/service_container/parent_services.rst index dcbbb582cd2..7ddd99788fe 100644 --- a/service_container/parent_services.rst +++ b/service_container/parent_services.rst @@ -92,6 +92,8 @@ duplicated service definitions: .. code-block:: php + use AppBundle\Repository\DoctrineUserRepository; + use AppBundle\Repository\DoctrinePostRepository; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\DefinitionDecorator; @@ -103,11 +105,11 @@ duplicated service definitions: // extend the app.base_doctrine_repository service $definition = new DefinitionDecorator('app.base_doctrine_repository'); - $definition->setClass('AppBundle\Repository\DoctrineUserRepository'); + $definition->setClass(DoctrineUserRepository::class); $container->setDefinition('app.user_repository', $definition); $definition = new DefinitionDecorator('app.base_doctrine_repository'); - $definition->setClass('AppBundle\Repository\DoctrinePostRepository'); + $definition->setClass(DoctrinePostRepository::class); $container->setDefinition('app.post_repository', $definition); // ... @@ -197,12 +199,14 @@ in the child class: .. code-block:: php + use AppBundle\Repository\DoctrineUserRepository; + use AppBundle\Repository\DoctrinePostRepository; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\DefinitionDecorator; // ... $definition = new DefinitionDecorator('app.base_doctrine_repository'); - $definition->setClass('AppBundle\Repository\DoctrineUserRepository'); + $definition->setClass(DoctrineUserRepository::class); // overrides the public setting of the parent service $definition->setPublic(false); // appends the '@app.username_checker' argument to the parent argument list @@ -210,7 +214,7 @@ in the child class: $container->setDefinition('app.user_repository', $definition); $definition = new DefinitionDecorator('app.base_doctrine_repository'); - $definition->setClass('AppBundle\Repository\DoctrinePostRepository'); + $definition->setClass(DoctrinePostRepository::class); // overrides the first argument $definition->replaceArgument(0, new Reference('doctrine.custom_entity_manager')); $container->setDefinition('app.post_repository', $definition); diff --git a/service_container/scopes.rst b/service_container/scopes.rst index f365f0b884b..5cf59135633 100644 --- a/service_container/scopes.rst +++ b/service_container/scopes.rst @@ -162,15 +162,14 @@ argument is the ``ClientConfiguration`` object: .. code-block:: php // app/config/services.php + use AppBundle\Mail\Mailer; use Symfony\Component\DependencyInjection\Definition; - $definition = $container->setDefinition( - 'my_mailer', - new Definition( - 'AppBundle\Mail\Mailer', - array(new Reference('client_configuration'), - )) - )->setScope('client'); + $definition = $container->setDefinition('my_mailer', new Definition( + Mailer::class, + array(new Reference('client_configuration'), + ))) + ->setScope('client'); .. _passing-container: @@ -235,11 +234,12 @@ The service configuration for this class would look something like this: .. code-block:: php // app/config/services.php + use AppBundle\Mail\Mailer; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; $container->setDefinition('my_mailer', new Definition( - 'AppBundle\Mail\Mailer', + Mailer::class, array(new Reference('service_container')) )); diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 79ad1e55f6d..4e9d08f04a7 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -40,11 +40,14 @@ the original service is lost: .. code-block:: php - $container->register('app.mailer', 'AppBundle\Mailer'); + use AppBundle\Mailer; + use AppBundle\DecoratingMailer; + + $container->register('app.mailer', Mailer::class); // this replaces the old app.mailer definition with the new one, the // old definition is lost - $container->register('app.mailer', 'AppBundle\DecoratingMailer'); + $container->register('app.mailer', DecoratingMailer::class); Most of the time, that's exactly what you want to do. But sometimes, you might want to decorate the old one instead. In this case, the @@ -88,10 +91,11 @@ a reference of the old one as ``app.decorating_mailer.inner``: .. code-block:: php + use AppBundle\DecoratingMailer; use Symfony\Component\DependencyInjection\Reference; // ... - $container->register('app.decorating_mailer', 'AppBundle\DecoratingMailer') + $container->register('app.decorating_mailer', DecoratingMailer::class) ->setDecoratedService('app.mailer') ->addArgument(new Reference('app.decorating_mailer.inner')) ->setPublic(false) @@ -152,9 +156,10 @@ convention, the old ``app.mailer`` service is renamed to .. code-block:: php + use AppBundle\DecoratingMailer; use Symfony\Component\DependencyInjection\Reference; - $container->register('app.decorating_mailer', 'AppBundle\DecoratingMailer') + $container->register('app.decorating_mailer', DecoratingMailer::class) ->setDecoratedService('foo', 'app.decorating_mailer.wooz') ->addArgument(new Reference('app.decorating_mailer.wooz')) // ... diff --git a/service_container/tags.rst b/service_container/tags.rst index 3d673679cea..75bd17607ec 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -16,8 +16,8 @@ to be used for a specific purpose. Take the following example: # app/config/services.yml services: - foo.twig.extension: - class: AppBundle\Extension\FooExtension + app.twig_extension: + class: AppBundle\Twig\AppExtension public: false tags: - { name: twig.extension } @@ -33,8 +33,8 @@ to be used for a specific purpose. Take the following example: @@ -45,16 +45,17 @@ to be used for a specific purpose. Take the following example: .. code-block:: php // app/config/services.php + use AppBundle\Twig\AppExtension; use Symfony\Component\DependencyInjection\Definition; - $definition = new Definition('AppBundle\Extension\FooExtension'); + $definition = new Definition(AppExtension::class); $definition->setPublic(false); $definition->addTag('twig.extension'); - $container->setDefinition('foo.twig.extension', $definition); + $container->setDefinition('app.twig_extension', $definition); The ``twig.extension`` tag is a special tag that the TwigBundle uses during configuration. By giving the service this ``twig.extension`` tag, -the bundle knows that the ``foo.twig.extension`` service should be registered +the bundle knows that the ``app.twig_extension`` service should be registered as a Twig extension with Twig. In other words, Twig finds all services tagged with ``twig.extension`` and automatically registers them as extensions. @@ -128,7 +129,9 @@ Then, define the chain as a service: .. code-block:: php - $container->register('app.mailer_transport_chain', 'AppBundle\Mail\TransportChain'); + use AppBundle\Mail\TransportChain; + + $container->register('app.mailer_transport_chain', TransportChain::class); Define Services with a Custom Tag ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/service_container/third_party.rst b/service_container/third_party.rst index 3068cef353f..3c29a02fa96 100644 --- a/service_container/third_party.rst +++ b/service_container/third_party.rst @@ -83,8 +83,10 @@ Configuring the service container is easy: .. code-block:: php // app/config/services.php + use AppBundle\Newsletter\NewsletterManager; + $container->setDefinition('app.newsletter_manager', new Definition( - 'AppBundle\Newsletter\NewsletterManager', + NewsletterManager::class, array( new Reference('mailer'), new Reference('templating'), diff --git a/session/locale_sticky_session.rst b/session/locale_sticky_session.rst index d9d96c4cb4e..fb3507a48e9 100644 --- a/session/locale_sticky_session.rst +++ b/session/locale_sticky_session.rst @@ -84,11 +84,12 @@ Then register the listener: .. code-block:: php + use AppBundle\EventListener\LocaleListener; use Symfony\Component\DependencyInjection\Definition; $container ->setDefinition('app.locale_listener', new Definition( - 'AppBundle\EventListener\LocaleListener', + LocaleListener::class, array('%kernel.default_locale%') )) ->addTag('kernel.event_subscriber') @@ -200,8 +201,10 @@ Then register the listener: .. code-block:: php // app/config/services.php + use AppBundle\EventListener\UserLocaleListener; + $container - ->register('app.user_locale_listener', 'AppBundle\EventListener\UserLocaleListener') + ->register('app.user_locale_listener', UserLocaleListener::class) ->addArgument('session') ->addTag( 'kernel.event_listener', diff --git a/session/proxy_examples.rst b/session/proxy_examples.rst index f360d0e5e22..0bab1eef5b1 100644 --- a/session/proxy_examples.rst +++ b/session/proxy_examples.rst @@ -38,7 +38,9 @@ Then, define a new service related to the custom session handler: .. code-block:: php // app/config/config.php - $container->register('app.session_handler', 'AppBundle\Session\CustomSessionHandler'); + use AppBundle\Session\CustomSessionHandler; + + $container->register('app.session_handler', CustomSessionHandler::class); Finally, use the ``framework.session.handler_id`` configuration option to tell Symfony to use your own session handler instead of the default one: diff --git a/setup/bundles.rst b/setup/bundles.rst index adc9472d837..286eb41a33f 100644 --- a/setup/bundles.rst +++ b/setup/bundles.rst @@ -183,7 +183,9 @@ Instead of checking the Symfony Kernel version, check the version of the specifi component. For example, the OptionsResolver API changed in its 2.6 version by adding a ``setDefined()`` method. The recommended check in this case would be:: - if (!method_exists('Symfony\Component\OptionsResolver\OptionsResolver', 'setDefined')) { + use Symfony\Component\OptionsResolver\OptionsResolver; + + if (!method_exists(OptionsResolver::class, 'setDefined')) { // code for the old OptionsResolver API } else { // code for the new OptionsResolver API diff --git a/templating/twig_extension.rst b/templating/twig_extension.rst index 754b4910939..2f4fe969493 100644 --- a/templating/twig_extension.rst +++ b/templating/twig_extension.rst @@ -92,10 +92,11 @@ Now you must let the Service Container know about your newly created Twig Extens .. code-block:: php // app/config/services.php + use AppBundle\Twig\AppExtension; use Symfony\Component\DependencyInjection\Definition; $container - ->register('app.twig_extension', '\AppBundle\Twig\AppExtension') + ->register('app.twig_extension', AppExtension::class) ->setPublic(false) ->addTag('twig.extension'); diff --git a/testing/database.rst b/testing/database.rst index 5eeb90ffd00..0b610715ddb 100644 --- a/testing/database.rst +++ b/testing/database.rst @@ -59,14 +59,17 @@ Suppose the class you want to test looks like this:: Since the ``ObjectManager`` gets injected into the class through the constructor, it's easy to pass a mock object within a test:: + use AppBundle\Entity\Employee; use AppBundle\Salary\SalaryCalculator; + use Doctrine\ORM\EntityRepository; + use Doctrine\Common\Persistence\ObjectManager; class SalaryCalculatorTest extends \PHPUnit_Framework_TestCase { public function testCalculateTotalSalary() { // First, mock the object to be used in the test - $employee = $this->createMock('\AppBundle\Entity\Employee'); + $employee = $this->createMock(Employee::class); $employee->expects($this->once()) ->method('getSalary') ->will($this->returnValue(1000)); @@ -76,7 +79,7 @@ it's easy to pass a mock object within a test:: // Now, mock the repository so it returns the mock of the employee $employeeRepository = $this - ->getMockBuilder('\Doctrine\ORM\EntityRepository') + ->getMockBuilder(EntityRepository::class) ->disableOriginalConstructor() ->getMock(); $employeeRepository->expects($this->once()) @@ -85,7 +88,7 @@ it's easy to pass a mock object within a test:: // Last, mock the EntityManager to return the mock of the repository $entityManager = $this - ->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager') + ->getMockBuilder(ObjectManager::class) ->disableOriginalConstructor() ->getMock(); $entityManager->expects($this->once()) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 482a2dcc063..4ac578b927c 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -175,7 +175,7 @@ tag so that the validation system knows about it: # app/config/services.yml services: - validator.contains_alphanumeric: + app.contains_alphanumeric_validator: class: AppBundle\Validator\Constraints\ContainsAlphanumericValidator tags: - { name: validator.constraint_validator } @@ -183,7 +183,7 @@ tag so that the validation system knows about it: .. code-block:: xml - + @@ -191,8 +191,10 @@ tag so that the validation system knows about it: .. code-block:: php // app/config/services.php + use AppBundle\Validator\Constraints\ContainsAlphanumericValidator; + $container - ->register('validator.contains_alphanumeric', 'AppBundle\Validator\Constraints\ContainsAlphanumericValidator') + ->register('app.contains_alphanumeric_validator', ContainsAlphanumericValidator::class) ->addTag('validator.constraint_validator'); Now, when Symfony looks for the ``ContainsAlphanumericValidator`` validator, it will