From 219b7f88713f162934ae238c09c26986e23db457 Mon Sep 17 00:00:00 2001 From: kunicmarko20 Date: Mon, 26 Feb 2018 23:24:22 +0100 Subject: [PATCH] improve naming --- best_practices/configuration.rst | 10 +-- best_practices/forms.rst | 6 +- bundles/configuration.rst | 6 +- components/asset.rst | 26 ++++---- components/browser_kit.rst | 4 +- components/config/definition.rst | 14 ++-- components/config/resources.rst | 6 +- components/console/helpers/dialoghelper.rst | 6 +- components/console/helpers/progressbar.rst | 46 ++++++------- components/console/helpers/questionhelper.rst | 8 +-- components/console/helpers/table.rst | 8 +-- components/dependency_injection.rst | 46 ++++++------- .../dependency_injection/compilation.rst | 42 ++++++------ components/dom_crawler.rst | 12 ++-- .../container_aware_dispatcher.rst | 4 +- .../event_dispatcher/traceable_dispatcher.rst | 4 +- components/expression_language.rst | 10 +-- components/expression_language/caching.rst | 12 ++-- components/expression_language/extending.rst | 10 +-- components/expression_language/syntax.rst | 28 ++++---- components/filesystem.rst | 62 ++++++++--------- components/finder.rst | 7 +- components/form.rst | 20 +++--- components/http_foundation.rst | 8 +-- .../http_foundation/session_configuration.rst | 10 +-- components/process.rst | 14 ++-- components/property_access.rst | 66 +++++++++---------- components/routing.rst | 18 ++--- components/security/authentication.rst | 6 +- components/security/authorization.rst | 5 +- components/security/firewall.rst | 6 +- components/serializer.rst | 10 +-- components/templating.rst | 4 +- components/translation/custom_formats.rst | 10 +-- components/yaml.rst | 4 +- console/coloring.rst | 4 +- controller/error_pages.rst | 8 +-- controller/soap_web_service.rst | 10 +-- controller/upload_file.rst | 12 ++-- create_framework/dependency_injection.rst | 40 +++++------ create_framework/event_dispatcher.rst | 4 +- create_framework/front_controller.rst | 8 +-- create_framework/http_foundation.rst | 16 ++--- .../http_kernel_controller_resolver.rst | 4 +- .../http_kernel_httpkernel_class.rst | 4 +- .../http_kernel_httpkernelinterface.rst | 4 +- create_framework/introduction.rst | 4 +- create_framework/routing.rst | 4 +- create_framework/separation_of_concerns.rst | 8 +-- create_framework/templating.rst | 12 ++-- doctrine.rst | 22 +++---- doctrine/associations.rst | 10 +-- doctrine/dbal.rst | 4 +- doctrine/mapping_model_classes.rst | 8 +-- doctrine/multiple_entity_managers.rst | 10 +-- doctrine/pdo_session_storage.rst | 2 +- doctrine/registration_form.rst | 12 ++-- doctrine/repository.rst | 4 +- event_dispatcher/method_behavior.rst | 12 ++-- form/data_transformers.rst | 28 ++++---- form/form_collections.rst | 14 ++-- form/form_dependencies.rst | 10 +-- forms.rst | 6 +- introduction/from_flat_php_to_symfony2.rst | 32 ++++----- introduction/symfony1.rst | 6 +- reference/dic_tags.rst | 4 +- reference/events.rst | 2 +- reference/forms/types/file.rst | 6 +- .../forms/types/options/group_by.rst.inc | 4 +- .../types/options/preferred_choices.rst.inc | 4 +- routing.rst | 32 ++++----- routing/conditions.rst | 6 +- routing/custom_route_loader.rst | 18 ++--- routing/external_resources.rst | 18 ++--- routing/extra_information.rst | 6 +- routing/hostname_pattern.rst | 38 +++++------ routing/optional_placeholders.rst | 18 ++--- routing/redirect_in_config.rst | 14 ++-- routing/redirect_trailing_slash.rst | 4 +- routing/requirements.rst | 20 +++--- routing/scheme.rst | 6 +- routing/service_container_parameters.rst | 12 ++-- routing/slash_in_parameter.rst | 6 +- security.rst | 6 +- security/custom_password_authenticator.rst | 2 +- security/form_login_setup.rst | 6 +- security/impersonating_user.rst | 4 +- service_container/parent_services.rst | 6 +- templating.rst | 12 ++-- templating/render_without_controller.rst | 12 ++-- testing.rst | 4 +- testing/doctrine.rst | 10 +-- translation/locale.rst | 6 +- validation.rst | 14 ++-- validation/raw_values.rst | 8 +-- validation/sequence_provider.rst | 8 +-- 96 files changed, 595 insertions(+), 601 deletions(-) diff --git a/best_practices/configuration.rst b/best_practices/configuration.rst index 3bff5b2dda4..59c17b29518 100644 --- a/best_practices/configuration.rst +++ b/best_practices/configuration.rst @@ -101,20 +101,20 @@ to control the number of posts to display on the blog homepage: # app/config/config.yml parameters: - homepage.num_items: 10 + homepage.number_of_items: 10 If you've done something like this in the past, it's likely that you've in fact *never* actually needed to change that value. Creating a configuration option for a value that you are never going to configure just isn't necessary. Our recommendation is to define these values as constants in your application. -You could, for example, define a ``NUM_ITEMS`` constant in the ``Post`` entity:: +You could, for example, define a ``NUMBER_OF_ITEMS`` constant in the ``Post`` entity:: // src/AppBundle/Entity/Post.php namespace AppBundle\Entity; class Post { - const NUM_ITEMS = 10; + const NUMBER_OF_ITEMS = 10; // ... } @@ -129,7 +129,7 @@ Constants can be used for example in your Twig templates thanks to the .. code-block:: html+twig

- Displaying the {{ constant('NUM_ITEMS', post) }} most recent results. + Displaying the {{ constant('NUMBER_OF_ITEMS', post) }} most recent results.

And Doctrine entities and repositories can now easily access these values, @@ -144,7 +144,7 @@ whereas they cannot access the container parameters: class PostRepository extends EntityRepository { - public function findLatest($limit = Post::NUM_ITEMS) + public function findLatest($limit = Post::NUMBER_OF_ITEMS) { // ... } diff --git a/best_practices/forms.rst b/best_practices/forms.rst index a53b7f35c6f..6c6dbeafca0 100644 --- a/best_practices/forms.rst +++ b/best_practices/forms.rst @@ -189,9 +189,9 @@ Handling a form submit usually follows a similar template: $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $em = $this->getDoctrine()->getManager(); - $em->persist($post); - $em->flush(); + $entityManager = $this->getDoctrine()->getManager(); + $entityManager->persist($post); + $entityManager->flush(); return $this->redirect($this->generateUrl( 'admin_post_show', diff --git a/bundles/configuration.rst b/bundles/configuration.rst index 8696b4709ec..d155ea86022 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -269,9 +269,9 @@ In your extension, you can load this and dynamically set its arguments:: $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $def = $container->getDefinition('acme.social.twitter_client'); - $def->replaceArgument(0, $config['twitter']['client_id']); - $def->replaceArgument(1, $config['twitter']['client_secret']); + $definition = $container->getDefinition('acme.social.twitter_client'); + $definition->replaceArgument(0, $config['twitter']['client_id']); + $definition->replaceArgument(1, $config['twitter']['client_secret']); } .. tip:: diff --git a/components/asset.rst b/components/asset.rst index 65f181eee5b..b3beb8306e2 100644 --- a/components/asset.rst +++ b/components/asset.rst @@ -169,9 +169,9 @@ that path over and over again:: use Symfony\Component\Asset\PathPackage; // ... - $package = new PathPackage('/static/images', new StaticVersionStrategy('v1')); + $pathPackage = new PathPackage('/static/images', new StaticVersionStrategy('v1')); - echo $package->getUrl('/logo.png'); + echo $pathPackage->getUrl('/logo.png'); // result: /static/images/logo.png?v1 Request Context Aware Assets @@ -185,13 +185,13 @@ class can take into account the context of the current request:: use Symfony\Component\Asset\Context\RequestStackContext; // ... - $package = new PathPackage( + $pathPackage = new PathPackage( '/static/images', new StaticVersionStrategy('v1'), new RequestStackContext($requestStack) ); - echo $package->getUrl('/logo.png'); + echo $pathPackage->getUrl('/logo.png'); // result: /somewhere/static/images/logo.png?v1 Now that the request context is set, the ``PathPackage`` will prepend the @@ -212,12 +212,12 @@ class to generate absolute URLs for their assets:: use Symfony\Component\Asset\UrlPackage; // ... - $package = new UrlPackage( + $urlPackage = new UrlPackage( 'http://static.example.com/images/', new StaticVersionStrategy('v1') ); - echo $package->getUrl('/logo.png'); + echo $urlPackage->getUrl('/logo.png'); // result: http://static.example.com/images/logo.png?v1 You can also pass a schema-agnostic URL:: @@ -225,12 +225,12 @@ You can also pass a schema-agnostic URL:: use Symfony\Component\Asset\UrlPackage; // ... - $package = new UrlPackage( + $urlPackage = new UrlPackage( '//static.example.com/images/', new StaticVersionStrategy('v1') ); - echo $package->getUrl('/logo.png'); + echo $urlPackage->getUrl('/logo.png'); // result: //static.example.com/images/logo.png?v1 This is useful because assets will automatically be requested via HTTPS if @@ -248,11 +248,11 @@ constructor:: '//static1.example.com/images/', '//static2.example.com/images/', ); - $package = new UrlPackage($urls, new StaticVersionStrategy('v1')); + $urlPackage = new UrlPackage($urls, new StaticVersionStrategy('v1')); - echo $package->getUrl('/logo.png'); + echo $urlPackage->getUrl('/logo.png'); // result: http://static1.example.com/images/logo.png?v1 - echo $package->getUrl('/icon.png'); + echo $urlPackage->getUrl('/icon.png'); // result: http://static2.example.com/images/icon.png?v1 For each asset, one of the URLs will be randomly used. But, the selection @@ -271,13 +271,13 @@ protocol-relative URLs for HTTPs requests, any base URL for HTTP requests):: use Symfony\Component\Asset\Context\RequestStackContext; // ... - $package = new UrlPackage( + $urlPackage = new UrlPackage( array('http://example.com/', 'https://example.com/'), new StaticVersionStrategy('v1'), new RequestStackContext($requestStack) ); - echo $package->getUrl('/logo.png'); + echo $urlPackage->getUrl('/logo.png'); // assuming the RequestStackContext says that we are on a secure host // result: https://example.com/logo.png?v1 diff --git a/components/browser_kit.rst b/components/browser_kit.rst index bbce0b46942..55e0525e1bd 100644 --- a/components/browser_kit.rst +++ b/components/browser_kit.rst @@ -140,8 +140,8 @@ retrieve any cookie while making requests with the client:: // Get cookie data $name = $cookie->getName(); $value = $cookie->getValue(); - $raw = $cookie->getRawValue(); - $secure = $cookie->isSecure(); + $rawValue = $cookie->getRawValue(); + $isSecure = $cookie->isSecure(); $isHttpOnly = $cookie->isHttpOnly(); $isExpired = $cookie->isExpired(); $expires = $cookie->getExpiresTime(); diff --git a/components/config/definition.rst b/components/config/definition.rst index 1bee8be6535..835e37c5be5 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -534,8 +534,8 @@ tree with ``append()``:: public function addParametersNode() { - $builder = new TreeBuilder(); - $node = $builder->root('parameters'); + $treeBuilder = new TreeBuilder(); + $node = $treeBuilder->root('parameters'); $node ->isRequired() @@ -772,18 +772,18 @@ Otherwise the result is a clean array of configuration values:: use Symfony\Component\Config\Definition\Processor; use Acme\DatabaseConfiguration; - $config1 = Yaml::parse( + $config = Yaml::parse( file_get_contents(__DIR__.'/src/Matthias/config/config.yml') ); - $config2 = Yaml::parse( + $extraConfig = Yaml::parse( file_get_contents(__DIR__.'/src/Matthias/config/config_extra.yml') ); - $configs = array($config1, $config2); + $configs = array($config, $extraConfig); $processor = new Processor(); - $configuration = new DatabaseConfiguration(); + $databaseConfiguration = new DatabaseConfiguration(); $processedConfiguration = $processor->processConfiguration( - $configuration, + $databaseConfiguration, $configs ); diff --git a/components/config/resources.rst b/components/config/resources.rst index 97924703158..1f56aa69ada 100644 --- a/components/config/resources.rst +++ b/components/config/resources.rst @@ -21,8 +21,8 @@ files. This can be done with the :class:`Symfony\\Component\\Config\\FileLocator $configDirectories = array(__DIR__.'/app/config'); - $locator = new FileLocator($configDirectories); - $yamlUserFiles = $locator->locate('users.yml', null, false); + $fileLocator = new FileLocator($configDirectories); + $yamlUserFiles = $fileLocator->locate('users.yml', null, false); The locator receives a collection of locations where it should look for files. The first argument of ``locate()`` is the name of the file to look @@ -84,7 +84,7 @@ the resource:: use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\DelegatingLoader; - $loaderResolver = new LoaderResolver(array(new YamlUserLoader($locator))); + $loaderResolver = new LoaderResolver(array(new YamlUserLoader($fileLocator))); $delegatingLoader = new DelegatingLoader($loaderResolver); $delegatingLoader->load(__DIR__.'/users.yml'); diff --git a/components/console/helpers/dialoghelper.rst b/components/console/helpers/dialoghelper.rst index 99349c077d6..cccf89d42cd 100644 --- a/components/console/helpers/dialoghelper.rst +++ b/components/console/helpers/dialoghelper.rst @@ -52,7 +52,7 @@ You can also ask question with more than a simple yes/no answer. For instance, if you want to know a bundle name, you can add this to your command:: // ... - $bundle = $dialog->ask( + $bundleName = $dialog->ask( $output, 'Please enter the name of the bundle', 'AcmeDemoBundle' @@ -71,7 +71,7 @@ will be autocompleted as the user types:: $dialog = $this->getHelper('dialog'); $bundleNames = array('AcmeDemoBundle', 'AcmeBlogBundle', 'AcmeStoreBundle'); - $name = $dialog->ask( + $bundleName = $dialog->ask( $output, 'Please enter the name of a bundle', 'FooBundle', @@ -109,7 +109,7 @@ be suffixed with ``Bundle``. You can validate that by using the method:: // ... - $bundle = $dialog->askAndValidate( + $bundleName = $dialog->askAndValidate( $output, 'Please enter the name of the bundle', function ($answer) { diff --git a/components/console/helpers/progressbar.rst b/components/console/helpers/progressbar.rst index c8765dbcf24..609ce77e08c 100644 --- a/components/console/helpers/progressbar.rst +++ b/components/console/helpers/progressbar.rst @@ -16,24 +16,24 @@ number of units, and advance the progress as the command executes:: use Symfony\Component\Console\Helper\ProgressBar; // creates a new progress bar (50 units) - $progress = new ProgressBar($output, 50); + $progressBar = new ProgressBar($output, 50); // starts and displays the progress bar - $progress->start(); + $progressBar->start(); $i = 0; while ($i++ < 50) { // ... do some work // advances the progress bar 1 unit - $progress->advance(); + $progressBar->advance(); // you can also advance the progress bar by more than 1 unit - // $progress->advance(3); + // $progressBar->advance(3); } // ensures that the progress bar is at 100% - $progress->finish(); + $progressBar->finish(); Instead of advancing the bar by a number of steps (with the :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::advance` method), @@ -64,7 +64,7 @@ If you don't know the number of steps in advance, just omit the steps argument when creating the :class:`Symfony\\Component\\Console\\Helper\\ProgressBar` instance:: - $progress = new ProgressBar($output); + $progressBar = new ProgressBar($output); The progress will then be displayed as a throbber: @@ -131,7 +131,7 @@ level of verbosity of the ``OutputInterface`` instance: Instead of relying on the verbosity mode of the current command, you can also force a format via ``setFormat()``:: - $bar->setFormat('verbose'); + $progressBar->setFormat('verbose'); The built-in formats are the following: @@ -153,7 +153,7 @@ Custom Formats Instead of using the built-in formats, you can also set your own:: - $bar->setFormat('%bar%'); + $progressBar->setFormat('%bar%'); This sets the format to only display the progress bar itself: @@ -180,7 +180,7 @@ current progress of the bar. Here is a list of the built-in placeholders: For instance, here is how you could set the format to be the same as the ``debug`` one:: - $bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%'); + $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%'); Notice the ``:6s`` part added to some placeholders? That's how you can tweak the appearance of the bar (formatting and alignment). The part after the colon @@ -191,8 +191,8 @@ also define global formats:: ProgressBar::setFormatDefinition('minimal', 'Progress: %percent%%'); - $bar = new ProgressBar($output, 3); - $bar->setFormat('minimal'); + $progressBar = new ProgressBar($output, 3); + $progressBar->setFormat('minimal'); This code defines a new ``minimal`` format that you can then use for your progress bars: @@ -216,8 +216,8 @@ variant:: ProgressBar::setFormatDefinition('minimal', '%percent%% %remaining%'); ProgressBar::setFormatDefinition('minimal_nomax', '%percent%%'); - $bar = new ProgressBar($output); - $bar->setFormat('minimal'); + $progressBar = new ProgressBar($output); + $progressBar->setFormat('minimal'); When displaying the progress bar, the format will automatically be set to ``minimal_nomax`` if the bar does not have a maximum number of steps like in @@ -246,16 +246,16 @@ Amongst the placeholders, ``bar`` is a bit special as all the characters used to display it can be customized:: // the finished part of the bar - $progress->setBarCharacter('='); + $progressBar->setBarCharacter('='); // the unfinished part of the bar - $progress->setEmptyBarCharacter(' '); + $progressBar->setEmptyBarCharacter(' '); // the progress character - $progress->setProgressCharacter('|'); + $progressBar->setProgressCharacter('|'); // the bar width - $progress->setBarWidth(50); + $progressBar->setBarWidth(50); .. caution:: @@ -265,17 +265,17 @@ to display it can be customized:: :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::setRedrawFrequency`, so it updates on only some iterations:: - $progress = new ProgressBar($output, 50000); - $progress->start(); + $progressBar = new ProgressBar($output, 50000); + $progressBar->start(); // update every 100 iterations - $progress->setRedrawFrequency(100); + $progressBar->setRedrawFrequency(100); $i = 0; while ($i++ < 50000) { // ... do some work - $progress->advance(); + $progressBar->advance(); } Custom Placeholders @@ -288,8 +288,8 @@ that displays the number of remaining steps:: ProgressBar::setPlaceholderFormatterDefinition( 'remaining_steps', - function (ProgressBar $bar, OutputInterface $output) { - return $bar->getMaxSteps() - $bar->getProgress(); + function (ProgressBar $progressBar, OutputInterface $output) { + return $progressBar->getMaxSteps() - $progressBar->getProgress(); } ); diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index 184d00053e5..521b6d8d82d 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -83,7 +83,7 @@ if you want to know a bundle name, you can add this to your command:: // ... $question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle'); - $bundle = $helper->ask($input, $output, $question); + $bundleName = $helper->ask($input, $output, $question); } The user will be asked "Please enter the name of the bundle". They can type @@ -179,7 +179,7 @@ will be autocompleted as the user types:: $question = new Question('Please enter the name of a bundle', 'FooBundle'); $question->setAutocompleterValues($bundles); - $name = $helper->ask($input, $output, $question); + $bundleName = $helper->ask($input, $output, $question); } Hiding the User's Response @@ -237,7 +237,7 @@ method:: return $value ? trim($value) : ''; }); - $name = $helper->ask($input, $output, $question); + $bundleName = $helper->ask($input, $output, $question); } .. caution:: @@ -275,7 +275,7 @@ method:: }); $question->setMaxAttempts(2); - $name = $helper->ask($input, $output, $question); + $bundleName = $helper->ask($input, $output, $question); } The ``$validator`` is a callback which handles the validation. It should diff --git a/components/console/helpers/table.rst b/components/console/helpers/table.rst index a63334911a4..dca380a4ee3 100644 --- a/components/console/helpers/table.rst +++ b/components/console/helpers/table.rst @@ -109,17 +109,17 @@ If the built-in styles do not fit your need, define your own:: use Symfony\Component\Console\Helper\TableStyle; // by default, this is based on the default style - $style = new TableStyle(); + $tableStyle = new TableStyle(); // customizes the style - $style + $tableStyle ->setHorizontalBorderChar('|') ->setVerticalBorderChar('-') ->setCrossingChar(' ') ; // uses the custom style for this table - $table->setStyle($style); + $table->setStyle($tableStyle); Here is a full list of things you can customize: @@ -137,7 +137,7 @@ Here is a full list of things you can customize: You can also register a style globally:: // registers the style under the colorful name - Table::setStyleDefinition('colorful', $style); + Table::setStyleDefinition('colorful', $tableStyle); // applies the custom style for the given table $table->setStyle('colorful'); diff --git a/components/dependency_injection.rst b/components/dependency_injection.rst index 7b50076940a..07de6cd8048 100644 --- a/components/dependency_injection.rst +++ b/components/dependency_injection.rst @@ -44,8 +44,8 @@ You can register this in the container as a service:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); - $container->register('mailer', 'Mailer'); + $containerBuilder = new ContainerBuilder(); + $containerBuilder->register('mailer', 'Mailer'); An improvement to the class to make it more flexible would be to allow the container to set the ``transport`` used. If you change the class @@ -67,8 +67,8 @@ Then you can set the choice of transport in the container:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); - $container + $containerBuilder = new ContainerBuilder(); + $containerBuilder ->register('mailer', 'Mailer') ->addArgument('sendmail'); @@ -82,9 +82,9 @@ the ``Mailer`` service's constructor argument:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); - $container->setParameter('mailer.transport', 'sendmail'); - $container + $containerBuilder = new ContainerBuilder(); + $containerBuilder->setParameter('mailer.transport', 'sendmail'); + $containerBuilder ->register('mailer', 'Mailer') ->addArgument('%mailer.transport%'); @@ -111,14 +111,14 @@ not exist yet. Use the ``Reference`` class to tell the container to inject the use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); - $container->setParameter('mailer.transport', 'sendmail'); - $container + $containerBuilder->setParameter('mailer.transport', 'sendmail'); + $containerBuilder ->register('mailer', 'Mailer') ->addArgument('%mailer.transport%'); - $container + $containerBuilder ->register('newsletter_manager', 'NewsletterManager') ->addArgument(new Reference('mailer')); @@ -143,14 +143,14 @@ If you do want to though then the container can call the setter method:: use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); - $container->setParameter('mailer.transport', 'sendmail'); - $container + $containerBuilder->setParameter('mailer.transport', 'sendmail'); + $containerBuilder ->register('mailer', 'Mailer') ->addArgument('%mailer.transport%'); - $container + $containerBuilder ->register('newsletter_manager', 'NewsletterManager') ->addMethodCall('setMailer', array(new Reference('mailer'))); @@ -159,11 +159,11 @@ like this:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); // ... - $newsletterManager = $container->get('newsletter_manager'); + $newsletterManager = $containerBuilder->get('newsletter_manager'); Avoiding your Code Becoming Dependent on the Container ------------------------------------------------------ @@ -197,8 +197,8 @@ Loading an XML config file:: use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; - $container = new ContainerBuilder(); - $loader = new XmlFileLoader($container, new FileLocator(__DIR__)); + $containerBuilder = new ContainerBuilder(); + $loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__)); $loader->load('services.xml'); Loading a YAML config file:: @@ -207,8 +207,8 @@ Loading a YAML config file:: use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; - $container = new ContainerBuilder(); - $loader = new YamlFileLoader($container, new FileLocator(__DIR__)); + $containerBuilder = new ContainerBuilder(); + $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__)); $loader->load('services.yml'); .. note:: @@ -223,8 +223,8 @@ into a separate config file and load it in a similar way:: use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; - $container = new ContainerBuilder(); - $loader = new PhpFileLoader($container, new FileLocator(__DIR__)); + $containerBuilder = new ContainerBuilder(); + $loader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__)); $loader->load('services.php'); You can now set up the ``newsletter_manager`` and ``mailer`` services using diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst index aa83fa5476e..32dc771931b 100644 --- a/components/dependency_injection/compilation.rst +++ b/components/dependency_injection/compilation.rst @@ -117,14 +117,14 @@ are loaded:: use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; - $container = new ContainerBuilder(); - $container->registerExtension(new AcmeDemoExtension); + $containerBuilder = new ContainerBuilder(); + $containerBuilder->registerExtension(new AcmeDemoExtension); - $loader = new YamlFileLoader($container, new FileLocator(__DIR__)); + $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__)); $loader->load('config.yml'); // ... - $container->compile(); + $containerBuilder->compile(); .. note:: @@ -263,11 +263,11 @@ file but also load a secondary one only if a certain parameter is set:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); $extension = new AcmeDemoExtension(); - $container->registerExtension($extension); - $container->loadFromExtension($extension->getAlias()); - $container->compile(); + $containerBuilder->registerExtension($extension); + $containerBuilder->loadFromExtension($extension->getAlias()); + $containerBuilder->compile(); .. note:: @@ -344,8 +344,8 @@ will then be called when the container is compiled:: use Symfony\Component\DependencyInjection\ContainerBuilder; - $container = new ContainerBuilder(); - $container->addCompilerPass(new CustomCompilerPass); + $containerBuilder = new ContainerBuilder(); + $containerBuilder->addCompilerPass(new CustomCompilerPass); .. note:: @@ -378,8 +378,8 @@ been run:: use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\PassConfig; - $container = new ContainerBuilder(); - $container->addCompilerPass( + $containerBuilder = new ContainerBuilder(); + $containerBuilder->addCompilerPass( new CustomCompilerPass, PassConfig::TYPE_AFTER_REMOVING ); @@ -407,11 +407,11 @@ makes dumping the compiled container easy:: require_once $file; $container = new ProjectServiceContainer(); } else { - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); // ... - $container->compile(); + $containerBuilder->compile(); - $dumper = new PhpDumper($container); + $dumper = new PhpDumper($containerBuilder); file_put_contents($file, $dumper->dump()); } @@ -426,11 +426,11 @@ dump it:: require_once $file; $container = new MyCachedContainer(); } else { - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); // ... - $container->compile(); + $containerBuilder->compile(); - $dumper = new PhpDumper($container); + $dumper = new PhpDumper($containerBuilder); file_put_contents( $file, $dumper->dump(array('class' => 'MyCachedContainer')) @@ -458,12 +458,12 @@ application:: require_once $file; $container = new MyCachedContainer(); } else { - $container = new ContainerBuilder(); + $containerBuilder = new ContainerBuilder(); // ... - $container->compile(); + $containerBuilder->compile(); if (!$isDebug) { - $dumper = new PhpDumper($container); + $dumper = new PhpDumper($containerBuilder); file_put_contents( $file, $dumper->dump(array('class' => 'MyCachedContainer')) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 7883028cf0d..edb82647dce 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -264,16 +264,16 @@ and :phpclass:`DOMNode` objects: .. code-block:: php - $document = new \DOMDocument(); - $document->loadXml(''); - $nodeList = $document->getElementsByTagName('node'); - $node = $document->getElementsByTagName('node')->item(0); + $domDocument = new \DOMDocument(); + $domDocument->loadXml(''); + $nodeList = $domDocument->getElementsByTagName('node'); + $node = $domDocument->getElementsByTagName('node')->item(0); - $crawler->addDocument($document); + $crawler->addDocument($domDocument); $crawler->addNodeList($nodeList); $crawler->addNodes(array($node)); $crawler->addNode($node); - $crawler->add($document); + $crawler->add($domDocument); .. _component-dom-crawler-dumping: diff --git a/components/event_dispatcher/container_aware_dispatcher.rst b/components/event_dispatcher/container_aware_dispatcher.rst index 245a1f44118..ce330df6be9 100644 --- a/components/event_dispatcher/container_aware_dispatcher.rst +++ b/components/event_dispatcher/container_aware_dispatcher.rst @@ -26,8 +26,8 @@ into the :class:`Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatc use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; - $container = new ContainerBuilder(); - $dispatcher = new ContainerAwareEventDispatcher($container); + $containerBuilder = new ContainerBuilder(); + $dispatcher = new ContainerAwareEventDispatcher($containerBuilder); Adding Listeners ---------------- diff --git a/components/event_dispatcher/traceable_dispatcher.rst b/components/event_dispatcher/traceable_dispatcher.rst index c91bcabf13d..57f05ba6e0d 100644 --- a/components/event_dispatcher/traceable_dispatcher.rst +++ b/components/event_dispatcher/traceable_dispatcher.rst @@ -15,10 +15,10 @@ Pass the event dispatcher to be wrapped and an instance of the use Symfony\Component\Stopwatch\Stopwatch; // the event dispatcher to debug - $eventDispatcher = ...; + $dispatcher = ...; $traceableEventDispatcher = new TraceableEventDispatcher( - $eventDispatcher, + $dispatcher, new Stopwatch() ); diff --git a/components/expression_language.rst b/components/expression_language.rst index 348096e5dd9..09865f6e5da 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -66,11 +66,11 @@ The main class of the component is use Symfony\Component\ExpressionLanguage\ExpressionLanguage; - $language = new ExpressionLanguage(); + $expressionLanguage = new ExpressionLanguage(); - var_dump($language->evaluate('1 + 2')); // displays 3 + var_dump($expressionLanguage->evaluate('1 + 2')); // displays 3 - var_dump($language->compile('1 + 2')); // displays (1 + 2) + var_dump($expressionLanguage->compile('1 + 2')); // displays (1 + 2) Expression Syntax ----------------- @@ -86,7 +86,7 @@ PHP type (including objects):: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; - $language = new ExpressionLanguage(); + $expressionLanguage = new ExpressionLanguage(); class Apple { @@ -96,7 +96,7 @@ PHP type (including objects):: $apple = new Apple(); $apple->variety = 'Honeycrisp'; - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'fruit.variety', array( 'fruit' => $apple, diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst index b06176a0375..dbb5a1310b3 100644 --- a/components/expression_language/caching.rst +++ b/components/expression_language/caching.rst @@ -36,8 +36,8 @@ in the object using the constructor:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Acme\ExpressionLanguage\ParserCache\MyDatabaseParserCache; - $cache = new MyDatabaseParserCache(...); - $language = new ExpressionLanguage($cache); + $databaseParserCache = new MyDatabaseParserCache(...); + $expressionLanguage = new ExpressionLanguage($databaseParserCache); .. note:: @@ -54,9 +54,9 @@ Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and // ... // the parse() method returns a ParsedExpression - $expression = $language->parse('1 + 4', array()); + $expression = $expressionLanguage->parse('1 + 4', array()); - var_dump($language->evaluate($expression)); // prints 5 + var_dump($expressionLanguage->evaluate($expression)); // prints 5 .. code-block:: php @@ -65,10 +65,10 @@ Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and $expression = new SerializedParsedExpression( '1 + 4', - serialize($language->parse('1 + 4', array())->getNodes()) + serialize($expressionLanguage->parse('1 + 4', array())->getNodes()) ); - var_dump($language->evaluate($expression)); // prints 5 + var_dump($expressionLanguage->evaluate($expression)); // prints 5 .. _DoctrineBridge: https://github.com/symfony/doctrine-bridge .. _`doctrine cache library`: http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/caching.html diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index 5c681a6e671..1cd5169b70e 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -33,8 +33,8 @@ This method has 3 arguments: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; - $language = new ExpressionLanguage(); - $language->register('lowercase', function ($str) { + $expressionLanguage = new ExpressionLanguage(); + $expressionLanguage->register('lowercase', function ($str) { return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str); }, function ($arguments, $str) { if (!is_string($str)) { @@ -44,7 +44,7 @@ This method has 3 arguments: return strtolower($str); }); - var_dump($language->evaluate('lowercase("HELLO")')); + var_dump($expressionLanguage->evaluate('lowercase("HELLO")')); This will print ``hello``. Both the **compiler** and **evaluator** are passed an ``arguments`` variable as their first argument, which is equal to the @@ -100,13 +100,13 @@ or by using the second argument of the constructor:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; // using the constructor - $language = new ExpressionLanguage(null, array( + $expressionLanguage = new ExpressionLanguage(null, array( new StringExpressionLanguageProvider(), // ... )); // using registerProvider() - $language->registerProvider(new StringExpressionLanguageProvider()); + $expressionLanguage->registerProvider(new StringExpressionLanguageProvider()); .. tip:: diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index c3140ace7a2..dae2c8c517a 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -25,8 +25,8 @@ The component supports: A backslash (``\``) must be escaped by 4 backslashes (``\\\\``) in a string and 8 backslashes (``\\\\\\\\``) in a regex:: - echo $language->evaluate('"\\\\"'); // prints \ - $language->evaluate('"a\\\\b" matches "/^a\\\\\\\\b$/"'); // returns true + echo $expressionLanguage->evaluate('"\\\\"'); // prints \ + $expressionLanguage->evaluate('"a\\\\b" matches "/^a\\\\\\\\b$/"'); // returns true Control characters (e.g. ``\n``) in expressions are replaced with whitespace. To avoid this, escape the sequence with a single backslash @@ -54,7 +54,7 @@ to JavaScript:: $apple = new Apple(); $apple->variety = 'Honeycrisp'; - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'fruit.variety', array( 'fruit' => $apple, @@ -84,7 +84,7 @@ JavaScript:: $robot = new Robot(); - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'robot.sayHi(3)', array( 'robot' => $robot, @@ -105,7 +105,7 @@ constant:: define('DB_USER', 'root'); - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'constant("DB_USER")' )); @@ -126,7 +126,7 @@ array keys, similar to JavaScript:: $data = array('life' => 10, 'universe' => 10, 'everything' => 22); - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'data["life"] + data["universe"] + data["everything"]', array( 'data' => $data, @@ -152,7 +152,7 @@ Arithmetic Operators For example:: - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'life + universe + everything', array( 'life' => 10, @@ -188,14 +188,14 @@ Comparison Operators To test if a string does *not* match a regex, use the logical ``not`` operator in combination with the ``matches`` operator:: - $language->evaluate('not ("foo" matches "/bar/")'); // returns true + $expressionLanguage->evaluate('not ("foo" matches "/bar/")'); // returns true You must use parenthesis because the unary operator ``not`` has precedence over the binary operator ``matches``. Examples:: - $ret1 = $language->evaluate( + $ret1 = $expressionLanguage->evaluate( 'life == everything', array( 'life' => 10, @@ -204,7 +204,7 @@ Examples:: ) ); - $ret2 = $language->evaluate( + $ret2 = $expressionLanguage->evaluate( 'life > everything', array( 'life' => 10, @@ -224,7 +224,7 @@ Logical Operators For example:: - $ret = $language->evaluate( + $ret = $expressionLanguage->evaluate( 'life < universe or life < everything', array( 'life' => 10, @@ -242,7 +242,7 @@ String Operators For example:: - var_dump($language->evaluate( + var_dump($expressionLanguage->evaluate( 'firstName~" "~lastName', array( 'firstName' => 'Arthur', @@ -268,7 +268,7 @@ For example:: $user = new User(); $user->group = 'human_resources'; - $inGroup = $language->evaluate( + $inGroup = $expressionLanguage->evaluate( 'user.group in ["human_resources", "marketing"]', array( 'user' => $user, @@ -292,7 +292,7 @@ For example:: $user = new User(); $user->age = 34; - $language->evaluate( + $expressionLanguage->evaluate( 'user.age in 18..45', array( 'user' => $user, diff --git a/components/filesystem.rst b/components/filesystem.rst index 5cd28433938..8a44b211a15 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -30,12 +30,12 @@ endpoint for filesystem operations:: use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOExceptionInterface; - $fs = new Filesystem(); + $fileSystem = new Filesystem(); try { - $fs->mkdir('/tmp/random/dir/'.mt_rand()); - } catch (IOExceptionInterface $e) { - echo "An error occurred while creating your directory at ".$e->getPath(); + $fileSystem->mkdir('/tmp/random/dir/'.mt_rand()); + } catch (IOExceptionInterface $exception) { + echo "An error occurred while creating your directory at ".$exception->getPath(); } .. note:: @@ -57,7 +57,7 @@ mkdir On POSIX filesystems, directories are created with a default mode value `0777`. You can use the second argument to set your own mode:: - $fs->mkdir('/tmp/photos', 0700); + $fileSystem->mkdir('/tmp/photos', 0700); .. note:: @@ -83,10 +83,10 @@ presence of one or more files or directories and returns ``false`` if any of them is missing:: // this directory exists, return true - $fs->exists('/tmp/photos'); + $fileSystem->exists('/tmp/photos'); // rabbit.jpg exists, bottle.png does not exist, return false - $fs->exists(array('rabbit.jpg', 'bottle.png')); + $fileSystem->exists(array('rabbit.jpg', 'bottle.png')); .. note:: @@ -103,10 +103,10 @@ source modification date is later than the target. This behavior can be overridd by the third boolean argument:: // works only if image-ICC has been modified after image.jpg - $fs->copy('image-ICC.jpg', 'image.jpg'); + $fileSystem->copy('image-ICC.jpg', 'image.jpg'); // image.jpg will be overridden - $fs->copy('image-ICC.jpg', 'image.jpg', true); + $fileSystem->copy('image-ICC.jpg', 'image.jpg', true); touch ~~~~~ @@ -116,11 +116,11 @@ modification time for a file. The current time is used by default. You can set your own with the second argument. The third argument is the access time:: // sets modification time to the current timestamp - $fs->touch('file.txt'); + $fileSystem->touch('file.txt'); // sets modification time 10 seconds in the future - $fs->touch('file.txt', time() + 10); + $fileSystem->touch('file.txt', time() + 10); // sets access time 10 seconds in the past - $fs->touch('file.txt', time(), time() - 10); + $fileSystem->touch('file.txt', time(), time() - 10); .. note:: @@ -134,9 +134,9 @@ chown a file. The third argument is a boolean recursive option:: // sets the owner of the lolcat video to www-data - $fs->chown('lolcat.mp4', 'www-data'); + $fileSystem->chown('lolcat.mp4', 'www-data'); // changes the owner of the video directory recursively - $fs->chown('/video', 'www-data', true); + $fileSystem->chown('/video', 'www-data', true); .. note:: @@ -150,9 +150,9 @@ chgrp a file. The third argument is a boolean recursive option:: // sets the group of the lolcat video to nginx - $fs->chgrp('lolcat.mp4', 'nginx'); + $fileSystem->chgrp('lolcat.mp4', 'nginx'); // changes the group of the video directory recursively - $fs->chgrp('/video', 'nginx', true); + $fileSystem->chgrp('/video', 'nginx', true); .. note:: @@ -166,9 +166,9 @@ chmod permissions of a file. The fourth argument is a boolean recursive option:: // sets the mode of the video to 0600 - $fs->chmod('video.ogg', 0600); + $fileSystem->chmod('video.ogg', 0600); // changes the mod of the src directory recursively - $fs->chmod('src', 0700, 0000, true); + $fileSystem->chmod('src', 0700, 0000, true); .. note:: @@ -181,7 +181,7 @@ remove :method:`Symfony\\Component\\Filesystem\\Filesystem::remove` deletes files, directories and symlinks:: - $fs->remove(array('symlink', '/path/to/directory', 'activity.log')); + $fileSystem->remove(array('symlink', '/path/to/directory', 'activity.log')); .. note:: @@ -195,9 +195,9 @@ rename of a single file or directory:: // renames a file - $fs->rename('/tmp/processed_video.ogg', '/path/to/store/video_647.ogg'); + $fileSystem->rename('/tmp/processed_video.ogg', '/path/to/store/video_647.ogg'); // renames a directory - $fs->rename('/tmp/files', '/path/to/store/files'); + $fileSystem->rename('/tmp/files', '/path/to/store/files'); symlink ~~~~~~~ @@ -207,10 +207,10 @@ symbolic link from the target to the destination. If the filesystem does not support symbolic links, a third boolean argument is available:: // creates a symbolic link - $fs->symlink('/path/to/source', '/path/to/destination'); + $fileSystem->symlink('/path/to/source', '/path/to/destination'); // duplicates the source directory if the filesystem // does not support symbolic links - $fs->symlink('/path/to/source', '/path/to/destination', true); + $fileSystem->symlink('/path/to/source', '/path/to/destination', true); makePathRelative ~~~~~~~~~~~~~~~~ @@ -219,12 +219,12 @@ makePathRelative absolute paths and returns the relative path from the second path to the first one:: // returns '../' - $fs->makePathRelative( + $fileSystem->makePathRelative( '/var/lib/symfony/src/Symfony/', '/var/lib/symfony/src/Symfony/Component' ); // returns 'videos/' - $fs->makePathRelative('/tmp/videos', '/tmp') + $fileSystem->makePathRelative('/tmp/videos', '/tmp') mirror ~~~~~~ @@ -234,7 +234,7 @@ contents of the source directory into the target one (use the :method:`Symfony\\Component\\Filesystem\\Filesystem::copy` method to copy single files):: - $fs->mirror('/path/to/source', '/path/to/target'); + $fileSystem->mirror('/path/to/source', '/path/to/target'); isAbsolutePath ~~~~~~~~~~~~~~ @@ -243,13 +243,13 @@ isAbsolutePath ``true`` if the given path is absolute, ``false`` otherwise:: // returns true - $fs->isAbsolutePath('/tmp'); + $fileSystem->isAbsolutePath('/tmp'); // returns true - $fs->isAbsolutePath('c:\\Windows'); + $fileSystem->isAbsolutePath('c:\\Windows'); // returns false - $fs->isAbsolutePath('tmp'); + $fileSystem->isAbsolutePath('tmp'); // returns false - $fs->isAbsolutePath('../dir'); + $fileSystem->isAbsolutePath('../dir'); dumpFile ~~~~~~~~ @@ -263,7 +263,7 @@ file first and then moves it to the new file location when it's finished. This means that the user will always see either the complete old file or complete new file (but never a partially-written file):: - $fs->dumpFile('file.txt', 'Hello World'); + $fileSystem->dumpFile('file.txt', 'Hello World'); The ``file.txt`` file contains ``Hello World`` now. diff --git a/components/finder.rst b/components/finder.rst index 2b75287f770..e87b40b242d 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -176,12 +176,9 @@ Sort the result by name or by type (directories first, then files):: You can also define your own sorting algorithm with ``sort()`` method:: - $sort = function (\SplFileInfo $a, \SplFileInfo $b) - { + $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealPath(), $b->getRealPath()); - }; - - $finder->sort($sort); + }); File Name ~~~~~~~~~ diff --git a/components/form.rst b/components/form.rst index 7fd14a66531..ee71d435d9a 100644 --- a/components/form.rst +++ b/components/form.rst @@ -184,17 +184,17 @@ to bootstrap or access Twig and add the :class:`Symfony\\Bridge\\Twig\\Extension // this file comes with TwigBridge $defaultFormTheme = 'form_div_layout.html.twig'; - $vendorDir = realpath(__DIR__.'/../vendor'); + $vendorDirectory = realpath(__DIR__.'/../vendor'); // the path to TwigBridge library so Twig can locate the // form_div_layout.html.twig file $appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable'); - $vendorTwigBridgeDir = dirname($appVariableReflection->getFileName()); + $vendorTwigBridgeDirectory = dirname($appVariableReflection->getFileName()); // the path to your other templates - $viewsDir = realpath(__DIR__.'/../views'); + $viewsDirectory = realpath(__DIR__.'/../views'); $twig = new Twig_Environment(new Twig_Loader_Filesystem(array( - $viewsDir, - $vendorTwigBridgeDir.'/Resources/views/Form', + $viewsDirectory, + $vendorTwigBridgeDirectory.'/Resources/views/Form', ))); $formEngine = new TwigRendererEngine(array($defaultFormTheme)); $formEngine->setEnvironment($twig); @@ -305,9 +305,9 @@ Your integration with the Validation component will look something like this:: use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Validator\Validation; - $vendorDir = realpath(__DIR__.'/../vendor'); - $vendorFormDir = $vendorDir.'/symfony/form'; - $vendorValidatorDir = $vendorDir.'/symfony/validator'; + $vendorDirectory = realpath(__DIR__.'/../vendor'); + $vendorFormDirectory = $vendorDir.'/symfony/form'; + $vendorValidatorDirectory = $vendorDirectory.'/symfony/validator'; // creates the validator - details will vary $validator = Validation::createValidator(); @@ -315,13 +315,13 @@ Your integration with the Validation component will look something like this:: // there are built-in translations for the core error messages $translator->addResource( 'xlf', - $vendorFormDir.'/Resources/translations/validators.en.xlf', + $vendorFormDirectory.'/Resources/translations/validators.en.xlf', 'en', 'validators' ); $translator->addResource( 'xlf', - $vendorValidatorDir.'/Resources/translations/validators.en.xlf', + $vendorValidatorDirectory.'/Resources/translations/validators.en.xlf', 'en', 'validators' ); diff --git a/components/http_foundation.rst b/components/http_foundation.rst index a7bfc9382f7..013ad0385d1 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -265,15 +265,15 @@ If you need to get full access to parsed data from ``Accept``, ``Accept-Language use Symfony\Component\HttpFoundation\AcceptHeader; - $accept = AcceptHeader::fromString($request->headers->get('Accept')); - if ($accept->has('text/html')) { - $item = $accept->get('text/html'); + $acceptHeader = AcceptHeader::fromString($request->headers->get('Accept')); + if ($acceptHeader->has('text/html')) { + $item = $acceptHeader->get('text/html'); $charset = $item->getAttribute('charset', 'utf-8'); $quality = $item->getQuality(); } // Accept header items are sorted by descending quality - $accepts = AcceptHeader::fromString($request->headers->get('Accept')) + $acceptHeaders = AcceptHeader::fromString($request->headers->get('Accept')) ->all(); Accessing other Data diff --git a/components/http_foundation/session_configuration.rst b/components/http_foundation/session_configuration.rst index 24854666878..ba7c95766ef 100644 --- a/components/http_foundation/session_configuration.rst +++ b/components/http_foundation/session_configuration.rst @@ -45,8 +45,8 @@ Example usage:: use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; - $storage = new NativeSessionStorage(array(), new NativeFileSessionHandler()); - $session = new Session($storage); + $sessionStorage = new NativeSessionStorage(array(), new NativeFileSessionHandler()); + $session = new Session($sessionStorage); .. note:: @@ -84,8 +84,8 @@ Example usage:: use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; $pdo = new \PDO(...); - $storage = new NativeSessionStorage(array(), new PdoSessionHandler($pdo)); - $session = new Session($storage); + $sessionStorage = new NativeSessionStorage(array(), new PdoSessionHandler($pdo)); + $session = new Session($sessionStorage); Configuring PHP Sessions ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -231,7 +231,7 @@ response headers. use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; $options['cache_limiter'] = session_cache_limiter(); - $storage = new NativeSessionStorage($options); + $sessionStorage = new NativeSessionStorage($options); Session Metadata ~~~~~~~~~~~~~~~~ diff --git a/components/process.rst b/components/process.rst index daef81e637b..84350ebae23 100644 --- a/components/process.rst +++ b/components/process.rst @@ -64,7 +64,7 @@ with a non-zero code):: $process->mustRun(); echo $process->getOutput(); - } catch (ProcessFailedException $e) { + } catch (ProcessFailedException $exception) { echo $e->getMessage(); } @@ -198,8 +198,8 @@ To make your code work better on all platforms, you might want to use the use Symfony\Component\Process\ProcessBuilder; - $builder = new ProcessBuilder(array('ls', '-lsa')); - $builder->getProcess()->run(); + $processBuilder = new ProcessBuilder(array('ls', '-lsa')); + $processBuilder->getProcess()->run(); .. versionadded:: 2.3 The :method:`ProcessBuilder::setPrefix` @@ -214,17 +214,17 @@ adapter:: use Symfony\Component\Process\ProcessBuilder; - $builder = new ProcessBuilder(); - $builder->setPrefix('/usr/bin/tar'); + $processBuilder = new ProcessBuilder(); + $processBuilder->setPrefix('/usr/bin/tar'); // '/usr/bin/tar' '--list' '--file=archive.tar.gz' - echo $builder + echo $processBuilder ->setArguments(array('--list', '--file=archive.tar.gz')) ->getProcess() ->getCommandLine(); // '/usr/bin/tar' '-xzf' 'archive.tar.gz' - echo $builder + echo $processBuilder ->setArguments(array('-xzf', 'archive.tar.gz')) ->getProcess() ->getCommandLine(); diff --git a/components/property_access.rst b/components/property_access.rst index c7338acd600..6167c842b48 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -29,7 +29,7 @@ default configuration:: use Symfony\Component\PropertyAccess\PropertyAccess; - $accessor = PropertyAccess::createPropertyAccessor(); + $propertyAccessor = PropertyAccess::createPropertyAccessor(); .. versionadded:: 2.3 The :method:`Symfony\\Component\\PropertyAccess\\PropertyAccess::createPropertyAccessor` @@ -47,8 +47,8 @@ method. This is done using the index notation that is used in PHP:: 'first_name' => 'Wouter', ); - var_dump($accessor->getValue($person, '[first_name]')); // 'Wouter' - var_dump($accessor->getValue($person, '[age]')); // null + var_dump($propertyAccessor->getValue($person, '[first_name]')); // 'Wouter' + var_dump($propertyAccessor->getValue($person, '[age]')); // null As you can see, the method will return ``null`` if the index does not exists. @@ -64,8 +64,8 @@ You can also use multi dimensional arrays:: ) ); - var_dump($accessor->getValue($persons, '[0][first_name]')); // 'Wouter' - var_dump($accessor->getValue($persons, '[1][first_name]')); // 'Ryan' + var_dump($propertyAccessor->getValue($persons, '[0][first_name]')); // 'Wouter' + var_dump($propertyAccessor->getValue($persons, '[1][first_name]')); // 'Ryan' Reading from Objects -------------------- @@ -82,13 +82,13 @@ To read from properties, use the "dot" notation:: $person = new Person(); $person->firstName = 'Wouter'; - var_dump($accessor->getValue($person, 'firstName')); // 'Wouter' + var_dump($propertyAccessor->getValue($person, 'firstName')); // 'Wouter' $child = new Person(); $child->firstName = 'Bar'; $person->children = array($child); - var_dump($accessor->getValue($person, 'children[0].firstName')); // 'Bar' + var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar' .. caution:: @@ -118,7 +118,7 @@ property name (``first_name`` becomes ``FirstName``) and prefixes it with $person = new Person(); - var_dump($accessor->getValue($person, 'first_name')); // 'Wouter' + var_dump($propertyAccessor->getValue($person, 'first_name')); // 'Wouter' Using Hassers/Issers ~~~~~~~~~~~~~~~~~~~~ @@ -146,10 +146,10 @@ getters, this means that you can do something like this:: $person = new Person(); - if ($accessor->getValue($person, 'author')) { + if ($propertyAccessor->getValue($person, 'author')) { var_dump('He is an author'); } - if ($accessor->getValue($person, 'children')) { + if ($propertyAccessor->getValue($person, 'children')) { var_dump('He has children'); } @@ -175,7 +175,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: $person = new Person(); - var_dump($accessor->getValue($person, 'Wouter')); // array(...) + var_dump($propertyAccessor->getValue($person, 'Wouter')); // array(...) .. _components-property-access-magic-call: @@ -209,11 +209,11 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert $person = new Person(); // enables PHP __call() magic method - $accessor = PropertyAccess::createPropertyAccessorBuilder() + $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableMagicCall() ->getPropertyAccessor(); - var_dump($accessor->getValue($person, 'wouter')); // array(...) + var_dump($propertyAccessor->getValue($person, 'wouter')); // array(...) .. versionadded:: 2.3 The use of magic ``__call()`` method was introduced in Symfony 2.3. @@ -235,9 +235,9 @@ method:: // ... $person = array(); - $accessor->setValue($person, '[first_name]', 'Wouter'); + $propertyAccessor->setValue($person, '[first_name]', 'Wouter'); - var_dump($accessor->getValue($person, '[first_name]')); // 'Wouter' + var_dump($propertyAccessor->getValue($person, '[first_name]')); // 'Wouter' // or // var_dump($person['first_name']); // 'Wouter' @@ -277,9 +277,9 @@ can use setters, the magic ``__set()`` method or properties to set values:: $person = new Person(); - $accessor->setValue($person, 'firstName', 'Wouter'); - $accessor->setValue($person, 'lastName', 'de Jong'); // setLastName is called - $accessor->setValue($person, 'children', array(new Person())); // __set is called + $propertyAccessor->setValue($person, 'firstName', 'Wouter'); + $propertyAccessor->setValue($person, 'lastName', 'de Jong'); // setLastName is called + $propertyAccessor->setValue($person, 'children', array(new Person())); // __set is called var_dump($person->firstName); // 'Wouter' var_dump($person->getLastName()); // 'de Jong' @@ -313,11 +313,11 @@ see `Enable other Features`_. $person = new Person(); // Enable magic __call - $accessor = PropertyAccess::createPropertyAccessorBuilder() + $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableMagicCall() ->getPropertyAccessor(); - $accessor->setValue($person, 'wouter', array(...)); + $propertyAccessor->setValue($person, 'wouter', array(...)); var_dump($person->getWouter()); // array(...) @@ -354,7 +354,7 @@ properties through *adder* and *remover* methods. } $person = new Person(); - $accessor->setValue($person, 'children', array('kevin', 'wouter')); + $propertyAccessor->setValue($person, 'children', array('kevin', 'wouter')); var_dump($person->getChildren()); // array('kevin', 'wouter') @@ -377,7 +377,7 @@ instead:: $person = new Person(); - if ($accessor->isReadable($person, 'firstName')) { + if ($propertyAccessor->isReadable($person, 'firstName')) { // ... } @@ -388,7 +388,7 @@ method to find out whether a property path can be updated:: $person = new Person(); - if ($accessor->isWritable($person, 'firstName')) { + if ($propertyAccessor->isWritable($person, 'firstName')) { // ... } @@ -416,13 +416,13 @@ You can also mix objects and arrays:: $person = new Person(); - $accessor->setValue($person, 'children[0]', new Person); + $propertyAccessor->setValue($person, 'children[0]', new Person); // equal to $person->getChildren()[0] = new Person() - $accessor->setValue($person, 'children[0].firstName', 'Wouter'); + $propertyAccessor->setValue($person, 'children[0].firstName', 'Wouter'); // equal to $person->getChildren()[0]->firstName = 'Wouter' - var_dump('Hello '.$accessor->getValue($person, 'children[0].firstName')); // 'Wouter' + var_dump('Hello '.$propertyAccessor->getValue($person, 'children[0].firstName')); // 'Wouter' // equal to $person->getChildren()[0]->firstName Enable other Features @@ -433,29 +433,29 @@ configured to enable extra features. To do that you could use the :class:`Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder`:: // ... - $accessorBuilder = PropertyAccess::createPropertyAccessorBuilder(); + $propertyAccessorBuilder = PropertyAccess::createPropertyAccessorBuilder(); // enables magic __call - $accessorBuilder->enableMagicCall(); + $propertyAccessorBuilder->enableMagicCall(); // disables magic __call - $accessorBuilder->disableMagicCall(); + $propertyAccessorBuilder->disableMagicCall(); // checks if magic __call handling is enabled - $accessorBuilder->isMagicCallEnabled(); // true or false + $propertyAccessorBuilder->isMagicCallEnabled(); // true or false // At the end get the configured property accessor - $accessor = $accessorBuilder->getPropertyAccessor(); + $propertyAccessor = $propertyAccessorBuilder->getPropertyAccessor(); // Or all in one - $accessor = PropertyAccess::createPropertyAccessorBuilder() + $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableMagicCall() ->getPropertyAccessor(); Or you can pass parameters directly to the constructor (not the recommended way):: // ... - $accessor = new PropertyAccessor(true); // this enables handling of magic __call + $propertyAccessor = new PropertyAccessor(true); // this enables handling of magic __call .. _Packagist: https://packagist.org/packages/symfony/property-access .. _The Inflector component: https://github.com/symfony/inflector diff --git a/components/routing.rst b/components/routing.rst index b1d6d69582b..25a8aa79294 100644 --- a/components/routing.rst +++ b/components/routing.rst @@ -262,9 +262,9 @@ To load this file, you can use the following code. This assumes that your use Symfony\Component\Routing\Loader\YamlFileLoader; // looks inside *this* directory - $locator = new FileLocator(array(__DIR__)); - $loader = new YamlFileLoader($locator); - $collection = $loader->load('routes.yml'); + $fileLocator = new FileLocator(array(__DIR__)); + $loader = new YamlFileLoader($fileLocator); + $routes = $loader->load('routes.yml'); Besides :class:`Symfony\\Component\\Routing\\Loader\\YamlFileLoader` there are two other loaders that work the same way: @@ -279,14 +279,14 @@ have to provide the name of a PHP file which returns a :class:`Symfony\\Componen use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add( + $routes = new RouteCollection(); + $routes->add( 'route_name', new Route('/foo', array('_controller' => 'ExampleController')) ); // ... - return $collection; + return $routes; Routes as Closures .................. @@ -301,7 +301,7 @@ calls a closure and uses the result as a :class:`Symfony\\Component\\Routing\\Ro }; $loader = new ClosureLoader(); - $collection = $loader->load($closure); + $routes = $loader->load($closure); Routes as Annotations ..................... @@ -334,11 +334,11 @@ path) or disable caching (if it's set to ``null``). The caching is done automatically in the background if you want to use it. A basic example of the :class:`Symfony\\Component\\Routing\\Router` class would look like:: - $locator = new FileLocator(array(__DIR__)); + $fileLocator = new FileLocator(array(__DIR__)); $requestContext = new RequestContext('/'); $router = new Router( - new YamlFileLoader($locator), + new YamlFileLoader($fileLocator), 'routes.yml', array('cache_dir' => __DIR__.'/cache'), $requestContext diff --git a/components/security/authentication.rst b/components/security/authentication.rst index 9321e275b92..b3a0aa67583 100644 --- a/components/security/authentication.rst +++ b/components/security/authentication.rst @@ -86,7 +86,7 @@ The default authentication manager is an instance of try { $authenticatedToken = $authenticationManager ->authenticate($unauthenticatedToken); - } catch (AuthenticationException $failed) { + } catch (AuthenticationException $exception) { // authentication failed } @@ -152,14 +152,14 @@ password was valid:: // an array of password encoders (see below) $encoderFactory = new EncoderFactory(...); - $provider = new DaoAuthenticationProvider( + $daoProvider = new DaoAuthenticationProvider( $userProvider, $userChecker, 'secured_area', $encoderFactory ); - $provider->authenticate($unauthenticatedToken); + $daoProvider->authenticate($unauthenticatedToken); .. note:: diff --git a/components/security/authorization.rst b/components/security/authorization.rst index bae43bab6c1..93dd80a7293 100644 --- a/components/security/authorization.rst +++ b/components/security/authorization.rst @@ -121,10 +121,7 @@ on a "remember-me" cookie, or even authenticated anonymously? use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; - $anonymousClass = AnonymousToken::class; - $rememberMeClass = RememberMeToken::class; - - $trustResolver = new AuthenticationTrustResolver($anonymousClass, $rememberMeClass); + $trustResolver = new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class); $authenticatedVoter = new AuthenticatedVoter($trustResolver); diff --git a/components/security/firewall.rst b/components/security/firewall.rst index 64603efb319..a4672901266 100644 --- a/components/security/firewall.rst +++ b/components/security/firewall.rst @@ -61,7 +61,7 @@ the user:: use Symfony\Component\HttpFoundation\RequestMatcher; use Symfony\Component\Security\Http\Firewall\ExceptionListener; - $map = new FirewallMap(); + $firewallMap = new FirewallMap(); $requestMatcher = new RequestMatcher('^/secured-area/'); @@ -70,7 +70,7 @@ the user:: $exceptionListener = new ExceptionListener(...); - $map->add($requestMatcher, $listeners, $exceptionListener); + $firewallMap->add($requestMatcher, $listeners, $exceptionListener); The firewall map will be given to the firewall as its first argument, together with the event dispatcher that is used by the :class:`Symfony\\Component\\HttpKernel\\HttpKernel`:: @@ -81,7 +81,7 @@ with the event dispatcher that is used by the :class:`Symfony\\Component\\HttpKe // the EventDispatcher used by the HttpKernel $dispatcher = ...; - $firewall = new Firewall($map, $dispatcher); + $firewall = new Firewall($firewallMap, $dispatcher); $dispatcher->addListener( KernelEvents::REQUEST, diff --git a/components/serializer.rst b/components/serializer.rst index 8d33d830626..c2669f05752 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -611,13 +611,13 @@ when such a case is encountered:: $member = new Member(); $member->setName('Kévin'); - $org = new Organization(); - $org->setName('Les-Tilleuls.coop'); - $org->setMembers(array($member)); + $organization = new Organization(); + $organization->setName('Les-Tilleuls.coop'); + $organization->setMembers(array($member)); - $member->setOrganization($org); + $member->setOrganization($organization); - echo $serializer->serialize($org, 'json'); // Throws a CircularReferenceException + echo $serializer->serialize($organization, 'json'); // Throws a CircularReferenceException The ``setCircularReferenceLimit()`` method of this normalizer sets the number of times it will serialize the same object before considering it a circular diff --git a/components/templating.rst b/components/templating.rst index 98ea31eb2dc..0b49f60266c 100644 --- a/components/templating.rst +++ b/components/templating.rst @@ -38,9 +38,9 @@ which uses the template reference to actually find and load the template:: use Symfony\Component\Templating\TemplateNameParser; use Symfony\Component\Templating\Loader\FilesystemLoader; - $loader = new FilesystemLoader(__DIR__.'/views/%name%'); + $filesystemLoader = new FilesystemLoader(__DIR__.'/views/%name%'); - $templating = new PhpEngine(new TemplateNameParser(), $loader); + $templating = new PhpEngine(new TemplateNameParser(), $filesystemLoader); echo $templating->render('hello.php', array('firstname' => 'Fabien')); diff --git a/components/translation/custom_formats.rst b/components/translation/custom_formats.rst index 14c6e65c8b0..79088b5e168 100644 --- a/components/translation/custom_formats.rst +++ b/components/translation/custom_formats.rst @@ -46,10 +46,10 @@ create the catalog that will be returned:: } } - $catalogue = new MessageCatalogue($locale); - $catalogue->add($messages, $domain); + $messageCatalogue = new MessageCatalogue($locale); + $messageCatalogue->add($messages, $domain); - return $catalogue; + return $messageCatalogue; } } @@ -112,8 +112,8 @@ YAML file are dumped into a text file with the custom format:: use Symfony\Component\Translation\Loader\YamlFileLoader; $loader = new YamlFileLoader(); - $catalogue = $loader->load(__DIR__ . '/translations/messages.fr_FR.yml' , 'fr_FR'); + $translations = $loader->load(__DIR__ . '/translations/messages.fr_FR.yml' , 'fr_FR'); $dumper = new MyFormatDumper(); - $dumper->dump($catalogue, array('path' => __DIR__.'/dumps')); + $dumper->dump($translations, array('path' => __DIR__.'/dumps')); diff --git a/components/yaml.rst b/components/yaml.rst index 93a8448609b..0f039f23240 100644 --- a/components/yaml.rst +++ b/components/yaml.rst @@ -121,8 +121,8 @@ error occurred: try { $value = Yaml::parse(file_get_contents('/path/to/file.yml')); - } catch (ParseException $e) { - printf("Unable to parse the YAML string: %s", $e->getMessage()); + } catch (ParseException $exception) { + printf("Unable to parse the YAML string: %s", $exception->getMessage()); } .. _components-yaml-dump: diff --git a/console/coloring.rst b/console/coloring.rst index 034c339fd11..475f62d84c5 100644 --- a/console/coloring.rst +++ b/console/coloring.rst @@ -40,8 +40,8 @@ It is possible to define your own styles using the use Symfony\Component\Console\Formatter\OutputFormatterStyle; // ... - $style = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink')); - $output->getFormatter()->setStyle('fire', $style); + $outputStyle = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink')); + $output->getFormatter()->setStyle('fire', $outputStyle); $output->writeln('foo'); diff --git a/controller/error_pages.rst b/controller/error_pages.rst index ca221a47b0e..1777d5fea63 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -187,13 +187,13 @@ To use this feature, you need to have a definition in your // app/config/routing_dev.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection( + $routes = new RouteCollection(); + $routes->addCollection( $loader->import('@TwigBundle/Resources/config/routing/errors.xml') ); - $collection->addPrefix("/_error"); + $routes->addPrefix("/_error"); - return $collection; + return $routes; If you're coming from an older version of Symfony, you might need to add this to your ``routing_dev.yml`` file. If you're starting from diff --git a/controller/soap_web_service.rst b/controller/soap_web_service.rst index 47908796beb..f198c8da58e 100644 --- a/controller/soap_web_service.rst +++ b/controller/soap_web_service.rst @@ -105,14 +105,14 @@ WSDL document can be retrieved via ``/soap?wsdl``. { public function indexAction() { - $server = new \SoapServer('/path/to/hello.wsdl'); - $server->setObject($this->get('hello_service')); + $soapServer = new \SoapServer('/path/to/hello.wsdl'); + $soapServer->setObject($this->get('hello_service')); $response = new Response(); $response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1'); ob_start(); - $server->handle(); + $soapServer->handle(); $response->setContent(ob_get_clean()); return $response; @@ -133,9 +133,9 @@ Below is an example calling the service using a `NuSOAP`_ client. This example assumes that the ``indexAction()`` in the controller above is accessible via the route ``/soap``:: - $client = new \Soapclient('http://example.com/app.php/soap?wsdl'); + $soapClient = new \Soapclient('http://example.com/app.php/soap?wsdl'); - $result = $client->call('hello', array('name' => 'Scott')); + $result = $soapClient->call('hello', array('name' => 'Scott')); An example WSDL is below. diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 62d681c4274..afa0ea2e730 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -241,25 +241,25 @@ logic to a separate service:: class FileUploader { - private $targetDir; + private $targetDirectory; - public function __construct($targetDir) + public function __construct($targetDirectory) { - $this->targetDir = $targetDir; + $this->targetDirectory = $targetDirectory; } public function upload(UploadedFile $file) { $fileName = md5(uniqid()).'.'.$file->guessExtension(); - $file->move($this->getTargetDir(), $fileName); + $file->move($this->getTargetDirectory(), $fileName); return $fileName; } - public function getTargetDir() + public function getTargetDirectory() { - return $this->targetDir; + return $this->targetDirectory; } } diff --git a/create_framework/dependency_injection.rst b/create_framework/dependency_injection.rst index 6ff749c3371..7378d775839 100644 --- a/create_framework/dependency_injection.rst +++ b/create_framework/dependency_injection.rst @@ -99,32 +99,32 @@ Create a new file to host the dependency injection container configuration:: use Symfony\Component\EventDispatcher; use Simplex\Framework; - $sc = new DependencyInjection\ContainerBuilder(); - $sc->register('context', Routing\RequestContext::class); - $sc->register('matcher', Routing\Matcher\UrlMatcher::class) + $containerBuilder = new DependencyInjection\ContainerBuilder(); + $containerBuilder->register('context', Routing\RequestContext::class); + $containerBuilder->register('matcher', Routing\Matcher\UrlMatcher::class) ->setArguments(array($routes, new Reference('context'))) ; - $sc->register('resolver', HttpKernel\Controller\ControllerResolver::class); + $containerBuilder->register('resolver', HttpKernel\Controller\ControllerResolver::class); - $sc->register('listener.router', HttpKernel\EventListener\RouterListener::class) + $containerBuilder->register('listener.router', HttpKernel\EventListener\RouterListener::class) ->setArguments(array(new Reference('matcher'))) ; - $sc->register('listener.response', HttpKernel\EventListener\ResponseListener::class) + $containerBuilder->register('listener.response', HttpKernel\EventListener\ResponseListener::class) ->setArguments(array('UTF-8')) ; - $sc->register('listener.exception', HttpKernel\EventListener\ExceptionListener::class) + $containerBuilder->register('listener.exception', HttpKernel\EventListener\ExceptionListener::class) ->setArguments(array('Calendar\Controller\ErrorController::exceptionAction')) ; - $sc->register('dispatcher', EventDispatcher\EventDispatcher::class) + $containerBuilder->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', Framework::class) + $containerBuilder->register('framework', Framework::class) ->setArguments(array(new Reference('dispatcher'), new Reference('resolver'))) ; - return $sc; + return $containerBuilder; The goal of this file is to configure your objects and their dependencies. Nothing is instantiated during this configuration step. This is purely a @@ -153,11 +153,11 @@ The front controller is now only about wiring everything together:: use Symfony\Component\HttpFoundation\Request; $routes = include __DIR__.'/../src/app.php'; - $sc = include __DIR__.'/../src/container.php'; + $container = include __DIR__.'/../src/container.php'; $request = Request::createFromGlobals(); - $response = $sc->get('framework')->handle($request); + $response = $container->get('framework')->handle($request); $response->send(); @@ -183,8 +183,8 @@ Now, here is how you can register a custom listener in the front controller:: // ... use Simplex\StringResponseListener; - $sc->register('listener.string_response', StringResposeListener::class); - $sc->getDefinition('dispatcher') + $container->register('listener.string_response', StringResposeListener::class); + $container->getDefinition('dispatcher') ->addMethodCall('addSubscriber', array(new Reference('listener.string_response'))) ; @@ -192,34 +192,34 @@ Beside describing your objects, the dependency injection container can also be configured via parameters. Let's create one that defines if we are in debug mode or not:: - $sc->setParameter('debug', true); + $container->setParameter('debug', true); - echo $sc->getParameter('debug'); + echo $container->getParameter('debug'); These parameters can be used when defining object definitions. Let's make the charset configurable:: // ... - $sc->register('listener.response', HttpKernel\EventListener\ResponseListener::class) + $container->register('listener.response', HttpKernel\EventListener\ResponseListener::class) ->setArguments(array('%charset%')) ; After this change, you must set the charset before using the response listener object:: - $sc->setParameter('charset', 'UTF-8'); + $container->setParameter('charset', 'UTF-8'); Instead of relying on the convention that the routes are defined by the ``$routes`` variables, let's use a parameter again:: // ... - $sc->register('matcher', Routing\Matcher\UrlMatcher::class) + $container->register('matcher', Routing\Matcher\UrlMatcher::class) ->setArguments(array('%routes%', new Reference('context'))) ; And the related change in the front controller:: - $sc->setParameter('routes', include __DIR__.'/../src/app.php'); + $container->setParameter('routes', include __DIR__.'/../src/app.php'); We have obviously barely scratched the surface of what you can do with the container: from class names as parameters, to overriding existing object diff --git a/create_framework/event_dispatcher.rst b/create_framework/event_dispatcher.rst index a75231be9e3..f740a8d39a6 100644 --- a/create_framework/event_dispatcher.rst +++ b/create_framework/event_dispatcher.rst @@ -67,9 +67,9 @@ the Response instance:: $arguments = $this->resolver->getArguments($request, $controller); $response = call_user_func_array($controller, $arguments); - } catch (ResourceNotFoundException $e) { + } catch (ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (\Exception $e) { + } catch (\Exception $exception) { $response = new Response('An error occurred', 500); } diff --git a/create_framework/front_controller.rst b/create_framework/front_controller.rst index 333af3bd011..8698865aa46 100644 --- a/create_framework/front_controller.rst +++ b/create_framework/front_controller.rst @@ -38,9 +38,9 @@ Let's see it in action:: // framework/index.php require_once __DIR__.'/init.php'; - $input = $request->get('name', 'World'); + $name = $request->get('name', 'World'); - $response->setContent(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'))); + $response->setContent(sprintf('Hello %s', htmlspecialchars($name, ENT_QUOTES, 'UTF-8'))); $response->send(); And for the "Goodbye" page:: @@ -98,8 +98,8 @@ Such a script might look like the following:: And here is for instance the new ``hello.php`` script:: // framework/hello.php - $input = $request->get('name', 'World'); - $response->setContent(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'))); + $name = $request->get('name', 'World'); + $response->setContent(sprintf('Hello %s', htmlspecialchars($name, ENT_QUOTES, 'UTF-8'))); In the ``front.php`` script, ``$map`` associates URL paths with their corresponding PHP script paths. diff --git a/create_framework/http_foundation.rst b/create_framework/http_foundation.rst index a5778af7180..a48cbfebaa3 100644 --- a/create_framework/http_foundation.rst +++ b/create_framework/http_foundation.rst @@ -18,27 +18,27 @@ Even if the "application" we wrote in the previous chapter was simple enough, it suffers from a few problems:: // framework/index.php - $input = $_GET['name']; + $name = $_GET['name']; - printf('Hello %s', $input); + printf('Hello %s', $name); First, if the ``name`` query parameter is not defined in the URL query string, you will get a PHP warning; so let's fix it:: // framework/index.php - $input = isset($_GET['name']) ? $_GET['name'] : 'World'; + $name = isset($_GET['name']) ? $_GET['name'] : 'World'; - printf('Hello %s', $input); + printf('Hello %s', $name); Then, this *application is not secure*. Can you believe it? Even this simple snippet of PHP code is vulnerable to one of the most widespread Internet security issue, XSS (Cross-Site Scripting). Here is a more secure version:: - $input = isset($_GET['name']) ? $_GET['name'] : 'World'; + $name = isset($_GET['name']) ? $_GET['name'] : 'World'; header('Content-Type: text/html; charset=utf-8'); - printf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')); + printf('Hello %s', htmlspecialchars($name, ENT_QUOTES, 'UTF-8')); .. note:: @@ -142,9 +142,9 @@ Now, let's rewrite our application by using the ``Request`` and the $request = Request::createFromGlobals(); - $input = $request->get('name', 'World'); + $name = $request->get('name', 'World'); - $response = new Response(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'))); + $response = new Response(sprintf('Hello %s', htmlspecialchars($name, ENT_QUOTES, 'UTF-8'))); $response->send(); diff --git a/create_framework/http_kernel_controller_resolver.rst b/create_framework/http_kernel_controller_resolver.rst index 8aa56e616f7..8c0e5a041cb 100644 --- a/create_framework/http_kernel_controller_resolver.rst +++ b/create_framework/http_kernel_controller_resolver.rst @@ -183,9 +183,9 @@ Let's conclude with the new version of our framework:: $arguments = $resolver->getArguments($request, $controller); $response = call_user_func_array($controller, $arguments); - } catch (Routing\Exception\ResourceNotFoundException $e) { + } catch (Routing\Exception\ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (Exception $e) { + } catch (Exception $exception) { $response = new Response('An error occurred', 500); } diff --git a/create_framework/http_kernel_httpkernel_class.rst b/create_framework/http_kernel_httpkernel_class.rst index 4b33629bdee..3f340b7bf57 100644 --- a/create_framework/http_kernel_httpkernel_class.rst +++ b/create_framework/http_kernel_httpkernel_class.rst @@ -132,8 +132,8 @@ instead of a full Response object:: { public function indexAction(Request $request, $year) { - $leapyear = new LeapYear(); - if ($leapyear->isLeapYear($year)) { + $leapYear = new LeapYear(); + if ($leapYear->isLeapYear($year)) { return 'Yep, this is a leap year! '; } diff --git a/create_framework/http_kernel_httpkernelinterface.rst b/create_framework/http_kernel_httpkernelinterface.rst index 99c49a1a273..310f4619a1a 100644 --- a/create_framework/http_kernel_httpkernelinterface.rst +++ b/create_framework/http_kernel_httpkernelinterface.rst @@ -73,8 +73,8 @@ to cache a response for 10 seconds, use the ``Response::setTtl()`` method:: // ... public function indexAction(Request $request, $year) { - $leapyear = new LeapYear(); - if ($leapyear->isLeapYear($year)) { + $leapYear = new LeapYear(); + if ($leapYear->isLeapYear($year)) { $response = new Response('Yep, this is a leap year!'); } else { $response = new Response('Nope, this is not a leap year.'); diff --git a/create_framework/introduction.rst b/create_framework/introduction.rst index aa6fcdea76c..196d1325f27 100644 --- a/create_framework/introduction.rst +++ b/create_framework/introduction.rst @@ -104,9 +104,9 @@ Instead of creating our framework from scratch, we are going to write the same start with the simplest web application we can think of in PHP:: // framework/index.php - $input = $_GET['name']; + $name = $_GET['name']; - printf('Hello %s', $input); + printf('Hello %s', $name); If you have PHP 5.4, you can use the PHP built-in server to test this great application in a browser (``http://localhost:4321/index.php?name=Fabien``): diff --git a/create_framework/routing.rst b/create_framework/routing.rst index 2aed62006e4..deaf9a02420 100644 --- a/create_framework/routing.rst +++ b/create_framework/routing.rst @@ -149,9 +149,9 @@ With this knowledge in mind, let's write the new version of our framework:: include sprintf(__DIR__.'/../src/pages/%s.php', $_route); $response = new Response(ob_get_clean()); - } catch (Routing\Exception\ResourceNotFoundException $e) { + } catch (Routing\Exception\ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (Exception $e) { + } catch (Exception $exception) { $response = new Response('An error occurred', 500); } diff --git a/create_framework/separation_of_concerns.rst b/create_framework/separation_of_concerns.rst index dfb4b64b8bd..a3c1265697e 100644 --- a/create_framework/separation_of_concerns.rst +++ b/create_framework/separation_of_concerns.rst @@ -46,9 +46,9 @@ request handling logic into its own ``Simplex\\Framework`` class:: $arguments = $this->resolver->getArguments($request, $controller); return call_user_func_array($controller, $arguments); - } catch (ResourceNotFoundException $e) { + } catch (ResourceNotFoundException $exception) { return new Response('Not Found', 404); - } catch (\Exception $e) { + } catch (\Exception $exception) { return new Response('An error occurred', 500); } } @@ -103,8 +103,8 @@ Move the controller to ``Calendar\Controller\LeapYearController``:: { public function indexAction(Request $request, $year) { - $leapyear = new LeapYear(); - if ($leapyear->isLeapYear($year)) { + $leapYear = new LeapYear(); + if ($leapYear->isLeapYear($year)) { return new Response('Yep, this is a leap year!'); } diff --git a/create_framework/templating.rst b/create_framework/templating.rst index cf1cdc011ee..a00f5b352fb 100644 --- a/create_framework/templating.rst +++ b/create_framework/templating.rst @@ -20,9 +20,9 @@ Change the template rendering part of the framework to read as follows:: try { $request->attributes->add($matcher->match($request->getPathInfo())); $response = call_user_func('render_template', $request); - } catch (Routing\Exception\ResourceNotFoundException $e) { + } catch (Routing\Exception\ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (Exception $e) { + } catch (Exception $exception) { $response = new Response('An error occurred', 500); } @@ -63,9 +63,9 @@ the ``_controller`` route attribute:: try { $request->attributes->add($matcher->match($request->getPathInfo())); $response = call_user_func($request->attributes->get('_controller'), $request); - } catch (Routing\Exception\ResourceNotFoundException $e) { + } catch (Routing\Exception\ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (Exception $e) { + } catch (Exception $exception) { $response = new Response('An error occurred', 500); } @@ -125,9 +125,9 @@ Here is the updated and improved version of our framework:: try { $request->attributes->add($matcher->match($request->getPathInfo())); $response = call_user_func($request->attributes->get('_controller'), $request); - } catch (Routing\Exception\ResourceNotFoundException $e) { + } catch (Routing\Exception\ResourceNotFoundException $exception) { $response = new Response('Not Found', 404); - } catch (Exception $e) { + } catch (Exception $exception) { $response = new Response('An error occurred', 500); } diff --git a/doctrine.rst b/doctrine.rst index 7436fcb008e..00de1cf1b58 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -463,13 +463,13 @@ a controller, this is pretty easy. Add the following method to the $product->setPrice(19.99); $product->setDescription('Ergonomic and stylish!'); - $em = $this->getDoctrine()->getManager(); + $entityManager = $this->getDoctrine()->getManager(); // tells Doctrine you want to (eventually) save the Product (no queries yet) - $em->persist($product); + $entityManager->persist($product); // actually executes the queries (i.e. the INSERT query) - $em->flush(); + $entityManager->flush(); return new Response('Saved new product with id '.$product->getId()); } @@ -636,8 +636,8 @@ you have a route that maps a product id to an update action in a controller:: public function updateAction($productId) { - $em = $this->getDoctrine()->getManager(); - $product = $em->getRepository(Product::class)->find($productId); + $entityManager = $this->getDoctrine()->getManager(); + $product = $entityManager->getRepository(Product::class)->find($productId); if (!$product) { throw $this->createNotFoundException( @@ -646,7 +646,7 @@ you have a route that maps a product id to an update action in a controller:: } $product->setName('New product name!'); - $em->flush(); + $entityManager->flush(); return $this->redirectToRoute('homepage'); } @@ -657,7 +657,7 @@ Updating an object involves just three steps: #. modifying the object; #. calling ``flush()`` on the entity manager. -Notice that calling ``$em->persist($product)`` isn't necessary. Recall that +Notice that calling ``$entityManager->persist($product)`` isn't necessary. Recall that this method simply tells Doctrine to manage or "watch" the ``$product`` object. In this case, since you fetched the ``$product`` object from Doctrine, it's already managed. @@ -668,8 +668,8 @@ Deleting an Object Deleting an object is very similar, but requires a call to the ``remove()`` method of the entity manager:: - $em->remove($product); - $em->flush(); + $entityManager->remove($product); + $entityManager->flush(); As you might expect, the ``remove()`` method notifies Doctrine that you'd like to remove the given object from the database. The actual ``DELETE`` query, @@ -703,8 +703,8 @@ Imagine that you want to query for products that cost more than ``19.99``, ordered from least to most expensive. You can use DQL, Doctrine's native SQL-like language, to construct a query for this scenario:: - $em = $this->getDoctrine()->getManager(); - $query = $em->createQuery( + $entityManager = $this->getDoctrine()->getManager(); + $query = $entityManager->createQuery( 'SELECT p FROM AppBundle:Product p WHERE p.price > :price diff --git a/doctrine/associations.rst b/doctrine/associations.rst index 3c82f38c1ca..9767353f295 100644 --- a/doctrine/associations.rst +++ b/doctrine/associations.rst @@ -249,10 +249,10 @@ Now you can see this new code in action! Imagine you're inside a controller:: // relates this product to the category $product->setCategory($category); - $em = $this->getDoctrine()->getManager(); - $em->persist($category); - $em->persist($product); - $em->flush(); + $entityManager = $this->getDoctrine()->getManager(); + $entityManager->persist($category); + $entityManager->persist($product); + $entityManager->flush(); return new Response( 'Saved new product with id: '.$product->getId() @@ -377,7 +377,7 @@ following method to the ``ProductRepository`` class:: try { return $query->getSingleResult(); - } catch (\Doctrine\ORM\NoResultException $e) { + } catch (\Doctrine\ORM\NoResultException $exception) { return null; } } diff --git a/doctrine/dbal.rst b/doctrine/dbal.rst index 0fe5d55ee97..37283f6dcdb 100644 --- a/doctrine/dbal.rst +++ b/doctrine/dbal.rst @@ -87,8 +87,8 @@ You can then access the Doctrine DBAL connection by accessing the { public function indexAction() { - $conn = $this->get('database_connection'); - $users = $conn->fetchAll('SELECT * FROM users'); + $connection = $this->get('database_connection'); + $users = $connection->fetchAll('SELECT * FROM users'); // ... } diff --git a/doctrine/mapping_model_classes.rst b/doctrine/mapping_model_classes.rst index ce11f3fc043..0186da91b0f 100644 --- a/doctrine/mapping_model_classes.rst +++ b/doctrine/mapping_model_classes.rst @@ -46,9 +46,9 @@ be adapted for your case:: parent::build($container); // ... - $modelDir = realpath(__DIR__.'/Resources/config/doctrine/model'); + $modelDirectory = realpath(__DIR__.'/Resources/config/doctrine/model'); $mappings = array( - $modelDir => Model::class, + $modelDirectory => Model::class, ); if (class_exists(DoctrineOrmMappingsPass::class)) { @@ -135,11 +135,11 @@ Annotations, XML, Yaml, PHP and StaticPHP. The arguments are: // ... private function buildMappingCompilerPass() { - $locator = new Definition(DefaultFileLocator::class, array( + $fileLocator = new Definition(DefaultFileLocator::class, array( array(realpath(__DIR__ . '/Resources/config/doctrine-base')), '.orm.xml' )); - $driver = new Definition(XmlDriver::class, array($locator)); + $driver = new Definition(XmlDriver::class, array($fileLocator)); return new DoctrineOrmMappingsPass( $driver, diff --git a/doctrine/multiple_entity_managers.rst b/doctrine/multiple_entity_managers.rst index 949c41112f5..d1624a9b307 100644 --- a/doctrine/multiple_entity_managers.rst +++ b/doctrine/multiple_entity_managers.rst @@ -196,13 +196,13 @@ the default entity manager (i.e. ``default``) is returned:: public function indexAction() { // All three return the "default" entity manager - $em = $this->get('doctrine')->getManager(); - $em = $this->get('doctrine')->getManager('default'); - $em = $this->get('doctrine.orm.default_entity_manager'); + $entityManager = $this->get('doctrine')->getManager(); + $entityManager = $this->get('doctrine')->getManager('default'); + $entityManager = $this->get('doctrine.orm.default_entity_manager'); // Both of these return the "customer" entity manager - $customerEm = $this->get('doctrine')->getManager('customer'); - $customerEm = $this->get('doctrine.orm.customer_entity_manager'); + $customerEntityManager = $this->get('doctrine')->getManager('customer'); + $customerEntityManager = $this->get('doctrine.orm.customer_entity_manager'); } } diff --git a/doctrine/pdo_session_storage.rst b/doctrine/pdo_session_storage.rst index 57ddfcc233d..1edaf2db8b7 100644 --- a/doctrine/pdo_session_storage.rst +++ b/doctrine/pdo_session_storage.rst @@ -222,7 +222,7 @@ to set up this table for you according to the database engine used:: try { $sessionHandlerService->createTable(); - } catch (\PDOException $e) { + } catch (\PDOException $exception) { // the table could not be created for some reason } diff --git a/doctrine/registration_form.rst b/doctrine/registration_form.rst index 1f155f534f6..2f38d1eadcd 100644 --- a/doctrine/registration_form.rst +++ b/doctrine/registration_form.rst @@ -248,9 +248,9 @@ into the database:: $user->setPassword($password); // 4) save the User! - $em = $this->getDoctrine()->getManager(); - $em->persist($user); - $em->flush(); + $entityManager = $this->getDoctrine()->getManager(); + $entityManager->persist($user); + $entityManager->flush(); // ... do any other work - like sending them an email, etc // maybe set a "flash" success message for the user @@ -338,12 +338,12 @@ the :ref:`user password encoding ` article. use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('user_registration', new Route('/register', array( + $routes = new RouteCollection(); + $routes->add('user_registration', new Route('/register', array( '_controller' => 'AppBundle:Registration:register', ))); - return $collection; + return $routes; Next, create the template: diff --git a/doctrine/repository.rst b/doctrine/repository.rst index 8a97ed1f638..0870b5a232b 100644 --- a/doctrine/repository.rst +++ b/doctrine/repository.rst @@ -89,8 +89,8 @@ You can use this new method just like the default finder methods of the reposito use AppBundle\Entity\Post; // ... - $em = $this->getDoctrine()->getManager(); - $products = $em->getRepository(Product::class) + $entityManager = $this->getDoctrine()->getManager(); + $products = $entityManager->getRepository(Product::class) ->findAllOrderedByName(); .. note:: diff --git a/event_dispatcher/method_behavior.rst b/event_dispatcher/method_behavior.rst index 3b25b0deb1a..f2889c6cece 100644 --- a/event_dispatcher/method_behavior.rst +++ b/event_dispatcher/method_behavior.rst @@ -26,10 +26,10 @@ method:: $bar = $event->getBar(); // the real method implementation is here - $ret = ...; + $returnValue = ...; // do something after the method - $event = new FilterSendReturnValue($ret); + $event = new FilterSendReturnValue($returnValue); $this->dispatcher->dispatch('foo.post_send', $event); return $event->getReturnValue(); @@ -40,7 +40,7 @@ In this example, two events are thrown: ``foo.pre_send``, before the method is executed, and ``foo.post_send`` after the method is executed. Each uses a custom Event class to communicate information to the listeners of the two events. These event classes would need to be created by you and should allow, -in this example, the variables ``$foo``, ``$bar`` and ``$ret`` to be retrieved +in this example, the variables ``$foo``, ``$bar`` and ``$returnValue`` to be retrieved and set by the listeners. For example, assuming the ``FilterSendReturnValue`` has a ``setReturnValue()`` @@ -50,8 +50,8 @@ method, one listener might look like this: public function onFooPostSend(FilterSendReturnValue $event) { - $ret = $event->getReturnValue(); - // modify the original ``$ret`` value + $returnValue = $event->getReturnValue(); + // modify the original ``$returnValue`` value - $event->setReturnValue($ret); + $event->setReturnValue($returnValue); } diff --git a/form/data_transformers.rst b/form/data_transformers.rst index 24b20edc847..74c3c7e2f34 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -165,11 +165,11 @@ to and from the issue number and the ``Issue`` object:: class IssueToNumberTransformer implements DataTransformerInterface { - private $manager; + private $objectManager; - public function __construct(ObjectManager $manager) + public function __construct(ObjectManager $objectManager) { - $this->manager = $manager; + $this->objectManager = $objectManager; } /** @@ -201,7 +201,7 @@ to and from the issue number and the ``Issue`` object:: return; } - $issue = $this->manager + $issue = $this->objectManager ->getRepository(Issue::class) // query for the issue with this id ->find($issueNumber) @@ -256,11 +256,11 @@ to be passed in. Then, you can easily create and add the transformer:: // ... class TaskType extends AbstractType { - private $manager; + private $objectManager; - public function __construct(ObjectManager $manager) + public function __construct(ObjectManager $objectManager) { - $this->manager = $manager; + $this->objectManager = $objectManager; } public function buildForm(FormBuilderInterface $builder, array $options) @@ -275,7 +275,7 @@ to be passed in. Then, you can easily create and add the transformer:: // ... $builder->get('issue') - ->addModelTransformer(new IssueToNumberTransformer($this->manager)); + ->addModelTransformer(new IssueToNumberTransformer($this->objectManager)); } // ... @@ -284,8 +284,8 @@ to be passed in. Then, you can easily create and add the transformer:: Now, when you create your ``TaskType``, you'll need to pass in the entity manager:: // e.g. in a controller somewhere - $manager = $this->getDoctrine()->getManager(); - $form = $this->createForm(new TaskType($manager), $task); + $entityManager = $this->getDoctrine()->getManager(); + $form = $this->createForm(new TaskType($entityManager), $task); // ... @@ -336,16 +336,16 @@ First, create the custom field type class:: class IssueSelectorType extends AbstractType { - private $manager; + private $objectManager; - public function __construct(ObjectManager $manager) + public function __construct(ObjectManager $objectManager) { - $this->manager = $manager; + $this->objectManager = $objectManager; } public function buildForm(FormBuilderInterface $builder, array $options) { - $transformer = new IssueToNumberTransformer($this->manager); + $transformer = new IssueToNumberTransformer($this->objectManager); $builder->addModelTransformer($transformer); } diff --git a/form/form_collections.rst b/form/form_collections.rst index 4a446121dc0..a3455a48b6c 100644 --- a/form/form_collections.rst +++ b/form/form_collections.rst @@ -493,7 +493,7 @@ you will learn about next!). To save the new tags with Doctrine, you need to consider a couple more things. First, unless you iterate over all of the new ``Tag`` objects and - call ``$em->persist($tag)`` on each, you'll receive an error from + call ``$entityManager->persist($tag)`` on each, you'll receive an error from Doctrine: A new entity was found through the relationship @@ -704,8 +704,8 @@ the relationship between the removed ``Tag`` and ``Task`` object. // ... public function editAction($id, Request $request) { - $em = $this->getDoctrine()->getManager(); - $task = $em->getRepository(Task::class)->find($id); + $entityManager = $this->getDoctrine()->getManager(); + $task = $entityManager->getRepository(Task::class)->find($id); if (!$task) { throw $this->createNotFoundException('No task found for id '.$id); @@ -733,15 +733,15 @@ the relationship between the removed ``Tag`` and ``Task`` object. // if it was a many-to-one relationship, remove the relationship like this // $tag->setTask(null); - $em->persist($tag); + $entityManager->persist($tag); // if you wanted to delete the Tag entirely, you can also do that - // $em->remove($tag); + // $entityManager->remove($tag); } } - $em->persist($task); - $em->flush(); + $entityManager->persist($task); + $entityManager->flush(); // redirect back to some edit page return $this->redirectToRoute('task_edit', array('id' => $id)); diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index e95a53776a1..b2ba31372d1 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -53,8 +53,8 @@ of your ``buildForm()`` method:: { public function buildForm(FormBuilderInterface $builder, array $options) { - /** @var \Doctrine\ORM\EntityManager $em */ - $em = $options['entity_manager']; + /** @var \Doctrine\ORM\EntityManager $entityManager */ + $entityManager = $options['entity_manager']; // ... } @@ -80,11 +80,11 @@ can make a query. First, add this as an argument to your form class:: class TaskType extends AbstractType { - private $em; + private $entityManager; - public function __construct(EntityManager $em) + public function __construct(EntityManager $entityManager) { - $this->em = $em; + $this->entityManager = $entityManager; } // ... diff --git a/forms.rst b/forms.rst index f20979236ab..7a61ce038da 100644 --- a/forms.rst +++ b/forms.rst @@ -240,9 +240,9 @@ your controller:: // ... perform some action, such as saving the task to the database // for example, if Task is a Doctrine entity, save it! - // $em = $this->getDoctrine()->getManager(); - // $em->persist($task); - // $em->flush(); + // $entityManager = $this->getDoctrine()->getManager(); + // $entityManager->persist($task); + // $entityManager->flush(); return $this->redirectToRoute('task_success'); } diff --git a/introduction/from_flat_php_to_symfony2.rst b/introduction/from_flat_php_to_symfony2.rst index 059b7676a9c..feb417e6f9d 100644 --- a/introduction/from_flat_php_to_symfony2.rst +++ b/introduction/from_flat_php_to_symfony2.rst @@ -33,9 +33,9 @@ persisted to the database. Writing in flat PHP is quick and dirty: query('SELECT id, title FROM post'); + $result = $connection->query('SELECT id, title FROM post'); ?> @@ -58,7 +58,7 @@ persisted to the database. Writing in flat PHP is quick and dirty: That's quick to write, fast to execute, and, as your app grows, impossible @@ -87,16 +87,16 @@ The code can immediately gain from separating the application "logic" from the code that prepares the HTML "presentation":: // index.php - $link = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword'); + $connection = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword'); - $result = $link->query('SELECT id, title FROM post'); + $result = $connection->query('SELECT id, title FROM post'); $posts = array(); while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $posts[] = $row; } - $link = null; + $connection = null; // include the HTML presentation code require 'templates/list.php'; @@ -147,27 +147,27 @@ of the application are isolated in a new file called ``model.php``:: // model.php function open_database_connection() { - $link = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword'); + $connection = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword'); - return $link; + return $connection; } - function close_database_connection(&$link) + function close_database_connection(&$connection) { - $link = null; + $connection = null; } function get_all_posts() { - $link = open_database_connection(); + $connection = open_database_connection(); - $result = $link->query('SELECT id, title FROM post'); + $result = $connection->query('SELECT id, title FROM post'); $posts = array(); while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $posts[] = $row; } - close_database_connection($link); + close_database_connection($connection); return $posts; } @@ -260,16 +260,16 @@ an individual blog result based on a given id:: // model.php function get_post_by_id($id) { - $link = open_database_connection(); + $connection = open_database_connection(); $query = 'SELECT created_at, title, body FROM post WHERE id=:id'; - $statement = $link->prepare($query); + $statement = $connection->prepare($query); $statement->bindValue(':id', $id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetch(PDO::FETCH_ASSOC); - close_database_connection($link); + close_database_connection($connection); return $row; } diff --git a/introduction/symfony1.rst b/introduction/symfony1.rst index da6eaac7dc6..1619df1a998 100644 --- a/introduction/symfony1.rst +++ b/introduction/symfony1.rst @@ -287,10 +287,10 @@ do the following: // app/config/routing.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection($loader->import("@AcmeHelloBundle/Resources/config/routing.php")); + $routes = new RouteCollection(); + $routes->addCollection($loader->import("@AcmeHelloBundle/Resources/config/routing.php")); - return $collection; + return $routes; This will load the routes found in the ``Resources/config/routing.yml`` file of the AcmeDemoBundle. The special ``@AcmeDemoBundle`` is a shortcut syntax diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 4e15795871a..74e7276dc8d 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -445,7 +445,7 @@ service class:: class MyClearer implements CacheClearerInterface { - public function clear($cacheDir) + public function clear($cacheDirectory) { // clear your cache } @@ -511,7 +511,7 @@ the :class:`Symfony\\Component\\HttpKernel\\CacheWarmer\\CacheWarmerInterface` i class MyCustomWarmer implements CacheWarmerInterface { - public function warmUp($cacheDir) + public function warmUp($cacheDirectory) { // ... do some sort of operations to "warm" your cache } diff --git a/reference/events.rst b/reference/events.rst index f81fcdee0f3..9cd8dd1b12b 100644 --- a/reference/events.rst +++ b/reference/events.rst @@ -91,7 +91,7 @@ HTML contents) into the ``Response`` object needed by Symfony:: public function onKernelView(GetResponseForControllerResultEvent $event) { - $val = $event->getControllerResult(); + $value = $event->getControllerResult(); $response = new Response(); // ... somehow customize the Response from the return value diff --git a/reference/forms/types/file.rst b/reference/forms/types/file.rst index 50e64d124b8..0a0add143d3 100644 --- a/reference/forms/types/file.rst +++ b/reference/forms/types/file.rst @@ -51,7 +51,7 @@ be used to move the ``attachment`` file to a permanent location:: $someNewFilename = ... $file = $form['attachment']->getData(); - $file->move($dir, $someNewFilename); + $file->move($directory, $someNewFilename); // ... } @@ -63,7 +63,7 @@ The ``move()`` method takes a directory and a file name as its arguments. You might calculate the filename in one of the following ways:: // use the original file name - $file->move($dir, $file->getClientOriginalName()); + $file->move($directory, $file->getClientOriginalName()); // compute a random name and try to guess the extension (more secure) $extension = $file->guessExtension(); @@ -71,7 +71,7 @@ You might calculate the filename in one of the following ways:: // extension cannot be guessed $extension = 'bin'; } - $file->move($dir, rand(1, 99999).'.'.$extension); + $file->move($directory, rand(1, 99999).'.'.$extension); Using the original name via ``getClientOriginalName()`` is not safe as it could have been manipulated by the end-user. Moreover, it can contain diff --git a/reference/forms/types/options/group_by.rst.inc b/reference/forms/types/options/group_by.rst.inc index 3628a39d388..aaa56e7d7b5 100644 --- a/reference/forms/types/options/group_by.rst.inc +++ b/reference/forms/types/options/group_by.rst.inc @@ -23,8 +23,8 @@ Take the following example:: '1 month' => new \DateTime('+1 month'), ), 'choices_as_values' => true, - 'group_by' => function($val, $key, $index) { - if ($val <= new \DateTime('+3 days')) { + 'group_by' => function($value, $key, $index) { + if ($value <= new \DateTime('+3 days')) { return 'Soon'; } else { return 'Later'; diff --git a/reference/forms/types/options/preferred_choices.rst.inc b/reference/forms/types/options/preferred_choices.rst.inc index 8393bd8cf4f..b1805ea9bc3 100644 --- a/reference/forms/types/options/preferred_choices.rst.inc +++ b/reference/forms/types/options/preferred_choices.rst.inc @@ -32,9 +32,9 @@ be especially useful if your values are objects:: '1 month' => new \DateTime('+1 month'), ), 'choices_as_values' => true, - 'preferred_choices' => function ($val, $key) { + 'preferred_choices' => function ($value, $key) { // prefer options within 3 days - return $val <= new \DateTime('+3 days'); + return $value <= new \DateTime('+3 days'); }, )); diff --git a/routing.rst b/routing.rst index 8fc048c2511..0c5b22ddbf4 100644 --- a/routing.rst +++ b/routing.rst @@ -103,15 +103,15 @@ The route is simple: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog_list', new Route('/blog', array( + $routes = new RouteCollection(); + $routes->add('blog_list', new Route('/blog', array( '_controller' => 'AppBundle:Blog:list', ))); - $collection->add('blog_show', new Route('/blog/{slug}', array( + $routes->add('blog_show', new Route('/blog/{slug}', array( '_controller' => 'AppBundle:Blog:show', ))); - return $collection; + return $routes; Thanks to these two routes: @@ -230,8 +230,8 @@ To fix this, add a *requirement* that the ``{page}`` wildcard can *only* match n use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog_list', new Route('/blog/{page}', array( + $routes = new RouteCollection(); + $routes->add('blog_list', new Route('/blog/{page}', array( '_controller' => 'AppBundle:Blog:list', ), array( 'page' => '\d+' @@ -239,7 +239,7 @@ To fix this, add a *requirement* that the ``{page}`` wildcard can *only* match n // ... - return $collection; + return $routes; The ``\d+`` is a regular expression that matches a *digit* of any length. Now: @@ -322,8 +322,8 @@ So how can you make ``blog_list`` once again match when the user visits use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog_list', new Route( + $routes = new RouteCollection(); + $routes->add('blog_list', new Route( '/blog/{page}', array( '_controller' => 'AppBundle:Blog:list', @@ -336,7 +336,7 @@ So how can you make ``blog_list`` once again match when the user visits // ... - return $collection; + return $routes; Now, when the user visits ``/blog``, the ``blog_list`` route will match and ``$page`` will default to a value of ``1``. @@ -415,8 +415,8 @@ With all of this in mind, check out this advanced example: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add( + $routes = new RouteCollection(); + $routes->add( 'article_show', new Route('/articles/{_locale}/{year}/{slug}.{_format}', array( '_controller' => 'AppBundle:Article:show', @@ -428,7 +428,7 @@ With all of this in mind, check out this advanced example: )) ); - return $collection; + return $routes; As you've seen, this route will only match if the ``{_locale}`` portion of the URL is either ``en`` or ``fr`` and if the ``{year}`` is a number. This @@ -589,14 +589,14 @@ sees our annotation routes: // app/config/routing.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection( + $routes = new RouteCollection(); + $routes->addCollection( // second argument is the type, which is required to enable // the annotation reader for this resource $loader->import("@AppBundle/Controller/", "annotation") ); - return $collection; + return $routes; For more details on loading routes, including how to prefix the paths of loaded routes, see :doc:`/routing/external_resources`. diff --git a/routing/conditions.rst b/routing/conditions.rst index 6358ff608f4..d3adf7bcc18 100644 --- a/routing/conditions.rst +++ b/routing/conditions.rst @@ -36,8 +36,8 @@ define arbitrary matching logic, use the ``conditions`` routing option: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('contact', new Route( + $routes = new RouteCollection(); + $routes->add('contact', new Route( '/contact', array( '_controller' => 'AcmeDemoBundle:Main:contact', ), @@ -75,7 +75,7 @@ variables that are passed into the expression: Behind the scenes, expressions are compiled down to raw PHP. Our example would generate the following PHP in the cache directory:: - if (rtrim($pathinfo, '/contact') === '' && ( + if (rtrim($pathInfo, '/contact') === '' && ( in_array($context->getMethod(), array(0 => "GET", 1 => "HEAD")) && preg_match("/firefox/i", $request->headers->get("User-Agent")) )) { diff --git a/routing/custom_route_loader.rst b/routing/custom_route_loader.rst index 0dbd3e0f920..5951eca9a96 100644 --- a/routing/custom_route_loader.rst +++ b/routing/custom_route_loader.rst @@ -84,11 +84,11 @@ you do. The resource name itself is not actually used in the example:: class ExtraLoader extends Loader { - private $loaded = false; + private $isLoaded = false; public function load($resource, $type = null) { - if (true === $this->loaded) { + if (true === $this->isLoaded) { throw new \RuntimeException('Do not add the "extra" loader twice'); } @@ -108,7 +108,7 @@ you do. The resource name itself is not actually used in the example:: $routeName = 'extraRoute'; $routes->add($routeName, $route); - $this->loaded = true; + $this->isLoaded = true; return $routes; } @@ -210,10 +210,10 @@ What remains to do is adding a few lines to the routing configuration: // app/config/routing.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection($loader->import('.', 'extra')); + $routes = new RouteCollection(); + $routes->addCollection($loader->import('.', 'extra')); - return $collection; + return $routes; The important part here is the ``type`` key. Its value should be "extra" as this is the type which the ``ExtraLoader`` supports and this will make sure @@ -252,16 +252,16 @@ configuration file - you can call the { public function load($resource, $type = null) { - $collection = new RouteCollection(); + $routes = new RouteCollection(); $resource = '@AppBundle/Resources/config/import_routing.yml'; $type = 'yaml'; $importedRoutes = $this->import($resource, $type); - $collection->addCollection($importedRoutes); + $routes->addCollection($importedRoutes); - return $collection; + return $routes; } public function supports($resource, $type = null) diff --git a/routing/external_resources.rst b/routing/external_resources.rst index 4c070d776d4..6732d46f1a6 100644 --- a/routing/external_resources.rst +++ b/routing/external_resources.rst @@ -36,14 +36,14 @@ This can be done by "importing" directories into the routing configuration: // app/config/routing.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection( + $routes = new RouteCollection(); + $routes->addCollection( // second argument is the type, which is required to enable // the annotation reader for this resource $loader->import("@AppBundle/Controller/", "annotation") ); - return $collection; + return $routes; .. note:: @@ -85,12 +85,12 @@ in that directory are parsed and put into the routing. // app/config/routing.php use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->addCollection( + $routes = new RouteCollection(); + $routes->addCollection( $loader->import("@AcmeOtherBundle/Resources/config/routing.php") ); - return $collection; + return $routes; .. _prefixing-imported-routes: @@ -146,10 +146,10 @@ suppose you want to prefix all routes in the AppBundle with ``/site`` (e.g. $app = $loader->import('@AppBundle/Controller/', 'annotation'); $app->addPrefix('/site'); - $collection = new RouteCollection(); - $collection->addCollection($app); + $routes = new RouteCollection(); + $routes->addCollection($app); - return $collection; + return $routes; The path of each route being loaded from the new routing resource will now be prefixed with the string ``/site``. diff --git a/routing/extra_information.rst b/routing/extra_information.rst index a25166ea6f1..89b935785b6 100644 --- a/routing/extra_information.rst +++ b/routing/extra_information.rst @@ -43,14 +43,14 @@ to your controller, and as attributes of the ``Request`` object: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog', new Route('/blog/{page}', array( + $routes = new RouteCollection(); + $routes->add('blog', new Route('/blog/{page}', array( '_controller' => 'AppBundle:Blog:index', 'page' => 1, 'title' => 'Hello world!', ))); - return $collection; + return $routes; Now, you can access this extra parameter in your controller, as an argument to the controller method:: diff --git a/routing/hostname_pattern.rst b/routing/hostname_pattern.rst index 27de3228387..b78c9d15aee 100644 --- a/routing/hostname_pattern.rst +++ b/routing/hostname_pattern.rst @@ -68,16 +68,16 @@ You can also match on the HTTP *host* of the incoming request. use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('mobile_homepage', new Route('/', array( + $routes = new RouteCollection(); + $routes->add('mobile_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:mobileHomepage', ), array(), array(), 'm.example.com')); - $collection->add('homepage', new Route('/', array( + $routes->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage', ))); - return $collection; + return $routes; Both routes match the same path ``/``, however the first one will match only if the host is ``m.example.com``. @@ -150,16 +150,16 @@ you can use placeholders in your hostname: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('project_homepage', new Route('/', array( + $routes = new RouteCollection(); + $routes->add('project_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:projectsHomepage', ), array(), array(), '{project_name}.example.com')); - $collection->add('homepage', new Route('/', array( + $routes->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage', ))); - return $collection; + return $routes; You can also set requirements and default options for these placeholders. For instance, if you want to match both ``m.example.com`` and @@ -239,19 +239,19 @@ instance, if you want to match both ``m.example.com`` and use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('mobile_homepage', new Route('/', array( + $routes = new RouteCollection(); + $routes->add('mobile_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:mobileHomepage', 'subdomain' => 'm', ), array( 'subdomain' => 'm|mobile', ), array(), '{subdomain}.example.com')); - $collection->add('homepage', new Route('/', array( + $routes->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage', ))); - return $collection; + return $routes; .. tip:: @@ -332,19 +332,19 @@ instance, if you want to match both ``m.example.com`` and use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('mobile_homepage', new Route('/', array( + $routes = new RouteCollection(); + $routes->add('mobile_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:mobileHomepage', 'domain' => '%domain%', ), array( 'domain' => '%domain%', ), array(), 'm.{domain}')); - $collection->add('homepage', new Route('/', array( + $routes->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage', ))); - return $collection; + return $routes; .. tip:: @@ -396,10 +396,10 @@ You can also set the host option on imported routes: .. code-block:: php - $collection = $loader->import("@AcmeHelloBundle/Resources/config/routing.php"); - $collection->setHost('hello.example.com'); + $routes = $loader->import("@AcmeHelloBundle/Resources/config/routing.php"); + $routes->setHost('hello.example.com'); - return $collection; + return $routes; The host ``hello.example.com`` will be set on each route loaded from the new routing resource. diff --git a/routing/optional_placeholders.rst b/routing/optional_placeholders.rst index 4d8b0a11a34..94941206a34 100644 --- a/routing/optional_placeholders.rst +++ b/routing/optional_placeholders.rst @@ -54,12 +54,12 @@ the available blog posts for this imaginary blog application: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog', new Route('/blog', array( + $routes = new RouteCollection(); + $routes->add('blog', new Route('/blog', array( '_controller' => 'AppBundle:Blog:index', ))); - return $collection; + return $routes; So far, this route is as simple as possible - it contains no placeholders and will only match the exact URL ``/blog``. But what if you need this route @@ -109,12 +109,12 @@ entries? Update the route to have a new ``{page}`` placeholder: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog', new Route('/blog/{page}', array( + $routes = new RouteCollection(); + $routes->add('blog', new Route('/blog/{page}', array( '_controller' => 'AppBundle:Blog:index', ))); - return $collection; + return $routes; Like the ``{slug}`` placeholder before, the value matching ``{page}`` will be available inside your controller. Its value can be used to determine which @@ -170,13 +170,13 @@ This is done by including it in the ``defaults`` collection: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog', new Route('/blog/{page}', array( + $routes = new RouteCollection(); + $routes->add('blog', new Route('/blog/{page}', array( '_controller' => 'AppBundle:Blog:index', 'page' => 1, ))); - return $collection; + return $routes; By adding ``page`` to the ``defaults`` key, the ``{page}`` placeholder is no longer required. The URL ``/blog`` will match this route and the value diff --git a/routing/redirect_in_config.rst b/routing/redirect_in_config.rst index f78c14e5305..6d7cf01fd49 100644 --- a/routing/redirect_in_config.rst +++ b/routing/redirect_in_config.rst @@ -69,22 +69,22 @@ action to redirect to this new url: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); + $routes = new RouteCollection(); // load some routes - one should ultimately have the path "/app" $appRoutes = $loader->import("@AppBundle/Controller/", "annotation"); $appRoutes->setPrefix('/app'); - $collection->addCollection($appRoutes); + $routes->addCollection($appRoutes); // redirecting the root - $collection->add('root', new Route('/', array( + $routes->add('root', new Route('/', array( '_controller' => 'FrameworkBundle:Redirect:urlRedirect', 'path' => '/app', 'permanent' => true, ))); - return $collection; + return $routes; In this example, you configured a route for the ``/`` path and let the ``RedirectController`` redirect it to ``/app``. The ``permanent`` switch @@ -141,17 +141,17 @@ action: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); + $routes = new RouteCollection(); // ... // redirecting the root - $collection->add('root', new Route('/wp-admin', array( + $routes->add('root', new Route('/wp-admin', array( '_controller' => 'FrameworkBundle:Redirect:redirect', 'route' => 'sonata_admin_dashboard', 'permanent' => true, ))); - return $collection; + return $routes; .. caution:: diff --git a/routing/redirect_trailing_slash.rst b/routing/redirect_trailing_slash.rst index 5233b535fff..a4a3d9a2936 100644 --- a/routing/redirect_trailing_slash.rst +++ b/routing/redirect_trailing_slash.rst @@ -83,8 +83,8 @@ system, as explained below: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add( + $routes = new RouteCollection(); + $routes->add( 'remove_trailing_slash', new Route( '/{url}', diff --git a/routing/requirements.rst b/routing/requirements.rst index f1efff3b664..6e7e2cbbe4f 100644 --- a/routing/requirements.rst +++ b/routing/requirements.rst @@ -61,8 +61,8 @@ a routing ``{wildcard}`` to only match some regular expression: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('blog_list', new Route('/blog/{page}', array( + $routes = new RouteCollection(); + $routes->add('blog_list', new Route('/blog/{page}', array( '_controller' => 'AppBundle:Blog:list', ), array( 'page' => '\d+', @@ -70,7 +70,7 @@ a routing ``{wildcard}`` to only match some regular expression: // ... - return $collection; + return $routes; Thanks to the ``\d+`` requirement (i.e. a "digit" of any length), ``/blog/2`` will match this route but ``/blog/some-string`` will *not* match. @@ -137,15 +137,15 @@ URL: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('homepage', new Route('/{_locale}', array( + $routes = new RouteCollection(); + $routes->add('homepage', new Route('/{_locale}', array( '_controller' => 'AppBundle:Main:homepage', '_locale' => 'en', ), array( '_locale' => 'en|fr', ))); - return $collection; + return $routes; For incoming requests, the ``{_locale}`` portion of the URL is matched against the regular expression ``(en|fr)``. @@ -248,16 +248,16 @@ accomplished with the following route configuration: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('api_post_show', new Route('/api/posts/{id}', array( + $routes = new RouteCollection(); + $routes->add('api_post_show', new Route('/api/posts/{id}', array( '_controller' => 'AppBundle:BlogApi:show', ), array(), array(), '', array(), array('GET', 'HEAD'))); - $collection->add('api_post_edit', new Route('/api/posts/{id}', array( + $routes->add('api_post_edit', new Route('/api/posts/{id}', array( '_controller' => 'AppBundle:BlogApi:edit', ), array(), array(), '', array(), array('PUT'))); - return $collection; + return $routes; Despite the fact that these two routes have identical paths (``/api/posts/{id}``), the first route will match only GET or HEAD requests and diff --git a/routing/scheme.rst b/routing/scheme.rst index 2f92232ee48..5fe798916ad 100644 --- a/routing/scheme.rst +++ b/routing/scheme.rst @@ -57,12 +57,12 @@ the URI scheme via schemes: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('secure', new Route('/secure', array( + $routes = new RouteCollection(); + $routes->add('secure', new Route('/secure', array( '_controller' => 'AppBundle:Main:secure', ), array(), array(), '', array('https'))); - return $collection; + return $routes; The above configuration forces the ``secure`` route to always use HTTPS. diff --git a/routing/service_container_parameters.rst b/routing/service_container_parameters.rst index 8e24657a40d..a3561e7ae19 100644 --- a/routing/service_container_parameters.rst +++ b/routing/service_container_parameters.rst @@ -46,14 +46,14 @@ inside your routing configuration: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('contact', new Route('/{_locale}/contact', array( + $routes = new RouteCollection(); + $routes->add('contact', new Route('/{_locale}/contact', array( '_controller' => 'AppBundle:Main:contact', ), array( '_locale' => '%app.locales%', ))); - return $collection; + return $routes; You can now control and set the ``app.locales`` parameter somewhere in your container: @@ -117,12 +117,12 @@ path): use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('some_route', new Route('/%app.route_prefix%/contact', array( + $routes = new RouteCollection(); + $routes->add('some_route', new Route('/%app.route_prefix%/contact', array( '_controller' => 'AppBundle:Main:contact', ))); - return $collection; + return $routes; .. note:: diff --git a/routing/slash_in_parameter.rst b/routing/slash_in_parameter.rst index 56714c135fc..d16e037b1c8 100644 --- a/routing/slash_in_parameter.rst +++ b/routing/slash_in_parameter.rst @@ -66,14 +66,14 @@ a more permissive regular expression for it: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('share', new Route('/share/{token}', array( + $routes = new RouteCollection(); + $routes->add('share', new Route('/share/{token}', array( '_controller' => 'AppBundle:Default:share', ), array( 'token' => '.+', ))); - return $collection; + return $routes; That's it! Now, the ``{token}`` parameter can contain the ``/`` character. diff --git a/security.rst b/security.rst index f52bd4b2875..b8db6fdd98b 100644 --- a/security.rst +++ b/security.rst @@ -1193,10 +1193,10 @@ Next, you'll need to create a route for this URL (but not a controller): use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('logout', new Route('/logout')); + $routes = new RouteCollection(); + $routes->add('logout', new Route('/logout')); - return $collection; + return $routes; And that's it! By sending a user to ``/logout`` (or whatever you configure the ``path`` to be), Symfony will un-authenticate the current user. diff --git a/security/custom_password_authenticator.rst b/security/custom_password_authenticator.rst index 9dc047ee14e..2e5991a4788 100644 --- a/security/custom_password_authenticator.rst +++ b/security/custom_password_authenticator.rst @@ -46,7 +46,7 @@ the user:: { try { $user = $userProvider->loadUserByUsername($token->getUsername()); - } catch (UsernameNotFoundException $e) { + } catch (UsernameNotFoundException $exception) { throw new AuthenticationException('Invalid username or password'); } diff --git a/security/form_login_setup.rst b/security/form_login_setup.rst index f254d10a33a..42779b999c7 100644 --- a/security/form_login_setup.rst +++ b/security/form_login_setup.rst @@ -131,12 +131,12 @@ configuration (``login``): use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('login', new Route('/login', array( + $routes = new RouteCollection(); + $routes->add('login', new Route('/login', array( '_controller' => 'AppBundle:Security:login', ))); - return $collection; + return $routes; Great! Next, add the logic to ``loginAction()`` that displays the login form:: diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index 0b34e0ce0c2..dc839e516af 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -109,10 +109,10 @@ over the user's roles until you find one that a ``SwitchUserRole`` object:: use Symfony\Component\Security\Core\Role\SwitchUserRole; - $authChecker = $this->get('security.authorization_checker'); + $authorizationChecker = $this->get('security.authorization_checker'); $tokenStorage = $this->get('security.token_storage'); - if ($authChecker->isGranted('ROLE_PREVIOUS_ADMIN')) { + if ($authorizationChecker->isGranted('ROLE_PREVIOUS_ADMIN')) { foreach ($tokenStorage->getToken()->getRoles() as $role) { if ($role instanceof SwitchUserRole) { $impersonatorUser = $role->getSource()->getUser(); diff --git a/service_container/parent_services.rst b/service_container/parent_services.rst index 496c1e1f7b9..4701d19cf65 100644 --- a/service_container/parent_services.rst +++ b/service_container/parent_services.rst @@ -15,12 +15,12 @@ you may have multiple repository classes which need the // ... abstract class BaseDoctrineRepository { - protected $entityManager; + protected $objectManager; protected $logger; - public function __construct(ObjectManager $manager) + public function __construct(ObjectManager $objectManager) { - $this->entityManager = $manager; + $this->objectManager = $objectManager; } public function setLogger(LoggerInterface $logger) diff --git a/templating.rst b/templating.rst index 296c3b40974..a2e40f4cfb0 100644 --- a/templating.rst +++ b/templating.rst @@ -617,12 +617,12 @@ configuration: use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->add('welcome', new Route('/', array( + $routes = new RouteCollection(); + $routes->add('welcome', new Route('/', array( '_controller' => 'AppBundle:Welcome:index', ))); - return $collection; + return $routes; To link to the page, just use the ``path()`` Twig function and refer to the route: @@ -686,12 +686,12 @@ route: use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; - $collection = new RouteCollection(); - $collection->add('article_show', new Route('/article/{slug}', array( + $routes = new RouteCollection(); + $routes->add('article_show', new Route('/article/{slug}', array( '_controller' => 'AppBundle:Article:show', ))); - return $collection; + return $routes; In this case, you need to specify both the route name (``article_show``) and a value for the ``{slug}`` parameter. Using this route, revisit the diff --git a/templating/render_without_controller.rst b/templating/render_without_controller.rst index 20e2ca240c3..f97a4b50735 100644 --- a/templating/render_without_controller.rst +++ b/templating/render_without_controller.rst @@ -42,13 +42,13 @@ can do this without creating a controller: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('acme_privacy', new Route('/privacy', array( + $routes = new RouteCollection(); + $routes->add('acme_privacy', new Route('/privacy', array( '_controller' => 'FrameworkBundle:Template:template', 'template' => 'static/privacy.html.twig', ))); - return $collection; + return $routes; The ``FrameworkBundle:Template:template`` controller will simply render whatever template you've passed as the ``template`` default value. @@ -116,15 +116,15 @@ other variables in your route, you can control exactly how your page is cached: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('acme_privacy', new Route('/privacy', array( + $routes = new RouteCollection(); + $routes->add('acme_privacy', new Route('/privacy', array( '_controller' => 'FrameworkBundle:Template:template', 'template' => 'static/privacy.html.twig', 'maxAge' => 86400, 'sharedAge' => 86400, ))); - return $collection; + return $routes; The ``maxAge`` and ``sharedAge`` values are used to modify the Response object created in the controller. For more information on caching, see diff --git a/testing.rst b/testing.rst index 19d7332e2f8..34d3b4b04fc 100644 --- a/testing.rst +++ b/testing.rst @@ -78,8 +78,8 @@ of your bundle:: { public function testAdd() { - $calc = new Calculator(); - $result = $calc->add(30, 12); + $calculator = new Calculator(); + $result = $calculator->add(30, 12); // assert that your calculator added the numbers correctly! $this->assertEquals(42, $result); diff --git a/testing/doctrine.rst b/testing/doctrine.rst index 67a30987733..908479eb49f 100644 --- a/testing/doctrine.rst +++ b/testing/doctrine.rst @@ -29,7 +29,7 @@ which makes all of this quite easy:: /** * @var \Doctrine\ORM\EntityManager */ - private $em; + private $entityManager; /** * {@inheritDoc} @@ -37,7 +37,7 @@ which makes all of this quite easy:: protected function setUp() { self::bootKernel(); - $this->em = static::$kernel->getContainer() + $this->entityManager = static::$kernel->getContainer() ->get('doctrine') ->getManager() ; @@ -45,7 +45,7 @@ which makes all of this quite easy:: public function testSearchByCategoryName() { - $products = $this->em + $products = $this->entityManager ->getRepository(Product::class) ->searchByCategoryName('foo') ; @@ -60,7 +60,7 @@ which makes all of this quite easy:: { parent::tearDown(); - $this->em->close(); - $this->em = null; // avoid memory leaks + $this->entityManager->close(); + $this->entityManager = null; // avoid memory leaks } } diff --git a/translation/locale.rst b/translation/locale.rst index 89c94b28fd0..e3660bdb0d9 100644 --- a/translation/locale.rst +++ b/translation/locale.rst @@ -87,8 +87,8 @@ by the routing system using the special ``_locale`` parameter: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $collection = new RouteCollection(); - $collection->add('contact', new Route( + $routes = new RouteCollection(); + $routes->add('contact', new Route( '/{_locale}/contact', array( '_controller' => 'AppBundle:Contact:index', @@ -98,7 +98,7 @@ by the routing system using the special ``_locale`` parameter: ) )); - return $collection; + return $routes; When using the special ``_locale`` parameter in a route, the matched locale is *automatically set on the Request* and can be retrieved via the diff --git a/validation.rst b/validation.rst index 7431ac6ba70..9a4a234cb0e 100644 --- a/validation.rst +++ b/validation.rst @@ -627,7 +627,7 @@ as "getters". The benefit of this technique is that it allows you to validate your object dynamically. For example, suppose you want to make sure that a password field doesn't match the first name of the user (for security reasons). You can -do this by creating an ``isPasswordLegal()`` method, and then asserting that +do this by creating an ``isPasswordSafe()`` method, and then asserting that this method must return ``true``: .. configuration-block:: @@ -644,7 +644,7 @@ this method must return ``true``: /** * @Assert\IsTrue(message="The password cannot match your first name") */ - public function isPasswordLegal() + public function isPasswordSafe() { // ... return true or false } @@ -655,7 +655,7 @@ this method must return ``true``: # src/AppBundle/Resources/config/validation.yml AppBundle\Entity\Author: getters: - passwordLegal: + passwordSafe: - 'IsTrue': { message: 'The password cannot match your first name' } .. code-block:: xml @@ -668,7 +668,7 @@ this method must return ``true``: http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd"> - + @@ -688,15 +688,15 @@ this method must return ``true``: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addGetterConstraint('passwordLegal', new Assert\IsTrue(array( + $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue(array( 'message' => 'The password cannot match your first name', ))); } } -Now, create the ``isPasswordLegal()`` method and include the logic you need:: +Now, create the ``isPasswordSafe()`` method and include the logic you need:: - public function isPasswordLegal() + public function isPasswordSafe() { return $this->firstName !== $this->password; } diff --git a/validation/raw_values.rst b/validation/raw_values.rst index 3ea6a5782f9..1928c2a2fbd 100644 --- a/validation/raw_values.rst +++ b/validation/raw_values.rst @@ -21,24 +21,24 @@ looks like this:: // use the validator to validate the value // If you're using the new 2.5 validation API (you probably are!) - $errorList = $this->get('validator')->validate( + $errors = $this->get('validator')->validate( $email, $emailConstraint ); // If you're using the old 2.4 validation API /* - $errorList = $this->get('validator')->validateValue( + $errors = $this->get('validator')->validateValue( $email, $emailConstraint ); */ - if (0 === count($errorList)) { + if (0 === count($errors)) { // ... this IS a valid email address, do something } else { // this is *not* a valid email address - $errorMessage = $errorList[0]->getMessage(); + $errorMessage = $errors[0]->getMessage(); // ... do something with the error } diff --git a/validation/sequence_provider.rst b/validation/sequence_provider.rst index 29582507021..c08661fe622 100644 --- a/validation/sequence_provider.rst +++ b/validation/sequence_provider.rst @@ -41,7 +41,7 @@ username and the password are different only if all other validation passes /** * @Assert\IsTrue(message="The password cannot match your username", groups={"Strict"}) */ - public function isPasswordLegal() + public function isPasswordSafe() { return ($this->username !== $this->password); } @@ -55,7 +55,7 @@ username and the password are different only if all other validation passes - User - Strict getters: - passwordLegal: + passwordSafe: - 'IsTrue': message: 'The password cannot match your username' groups: [Strict] @@ -82,7 +82,7 @@ username and the password are different only if all other validation passes - +