eZecosystem / Mirror / Symfony Blog

Symfony Flex is a recommended dependency of modern Symfony applications that improves your productivity by automating repetitive and boring tasks, like installing and automatically configuring bundles and other libraries.

Symfony Flex 1.2 has just been released with some useful new features!

Simpler update of recipes

Contributed by
Alex Rock
in #439.

Symfony Recipes define the instructions used by Symfony Flex to install and configure dependencies in your apps. We update recipes continuously to enable new features introduced by libraries or new configuration for a better experience. You don't need to apply these updated recipes to your application. But applying them can sometimes show you new features that you may want to use in your applications.

Symfony Flex already provides a sync-recipes command to install or reinstall recipes for the packages installed in an application. However, this command doesn't execute the recipe again if the recipe was already executed. And so, the updated version of a recipe is never applied to existing applications.

Symfony Flex 1.2 introduces the --force option to sync-recipes to unconditionally run all the recipes again for all packages. In practice, it means that Symfony will execute the latest recipe but you will lose any custom change that you made to the files affected by the recipes. The solution is to check the changes with git diff and apply/decline each recipe change:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$ composer sync-recipes --force

  Symfony operations: 10 recipes (8967ada4e2fe4a57735c35d43dd14035)
    - Configuring symfony/flex: From github.com/symfony/recipes:master
    - Configuring symfony/framework-bundle: From github.com/symfony/recipes:master
    - Configuring doctrine/doctrine-bundle: From github.com/symfony/recipes:master
    - ...

    * Use git diff to inspect the changes.

      Not all of the changes will be relevant to your app: you now
      need to selectively add or revert them using e.g. a combination
      of git add -p and git checkout -p

    * Use git checkout . to revert the changes.

      New (untracked) files can be inspected using git clean --dry-run
      Add the new files you want to keep using git add
      then delete the rest using git clean --force

Improved the handling of ``.env`` files

Contributed by
Nicolas Grekas
in #449 and #501.

If you created your Symfony application after December 2018 or if you have updated the recipes with sync-recipes --force recently, you'll see an important change related to the .env* config files.

These files are now always loaded, even if you set an APP_ENV=prod environment variable. The purpose is for the .env file to define default values that you can override with real environment values or by creating a .env.local file.

If you want to avoid parsing the .env* files on every request, Symfony Flex 1.2 includes a new dump-env command that compiles the contents of the .env* files into a PHP-optimized file called .env.local.php:

1
2
3
$ composer dump-env prod

  Successfully dumped .env files in .env.local.php

That file is then automatically read by the config/bootstrap.php file. And though this command is optional, it may be a good idea to run it during your deployment workflow to improve the application performance (same as you do with other commands such as composer dump-autoload -o).

Other improvements

Auto-installing multiple bundles

Contributed by
Edi Modrić
in #427.

Currently, any package with a symfony-bundle type in its composer.json file is enabled as a Symfony bundle when installing it, even if it doesn't have a Symfony Flex recipe defined for it.

Symfony Flex 1.2 now enables all the bundles found in the autoload configuration of the composer.json file, not only the first one.

Conflicting Recipes

Contributed by
Jules Pietri
in #464.

Recipes can now include a conflict key in their manifests to define the packages and versions which are not compatible with it. If a conflict is found when installing a recipe, Symfony Flex displays a message saying that a recipe installation was skipped and the reason for it:

1
2
3
4
5
6
7
{
    "...": "...",
    "conflict": {
        "symfony/messenger": "^4.2",
        "symfony/console": "<3.*"
    }
}

Be trained by Symfony experts - 2019-02-25 Berlin - 2019-02-25 Berlin - 2019-02-25 Clichy
02/21/2019 05:45 am   Symfony Blog   Mirror   Link  

Added a Twig function to get the parent form

Contributed by
Christian Flothmann
in #28812.

In Symfony 4.3 we added a Twig function called parent_form() which returns the parent form view or null if the form view already is the root form. Using this function should be preferred over accessing the parent form using form.parent. The latter way will produce different results for example when a child form is named parent.

Allow including HTML contents in help messages

Contributed by
Mathieu Piot
in #29861.

The contents of the help message that can be defined for form fields are escaped by default to prevent security issues. If your help messages contain HTML elements (e.g. links to other pages) and you know they are safe to render "as is", set to true the new help_html option added in Symfony 4.3:

1
2
3
4
$builder->add('zip_code', null, [
    'help' => '<a target="_blank" href="...">Look up your ZIP code.</a>',
    'help_html' => true,
]);

Configure the input format of DateType and DateTimeType

Contributed by
Thomas Calvet
in #29887.

In Symfony 4.3 we added a new input_format option to DateType and DateTimeType. If the input option is set to string, this option specifies the format of the date, which must be a valid PHP date format.

1
2
3
4
5
6
7
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;

$builder->add('startsAt', DateTimeType::class, [
    // ...,
    'input' => 'string',
    'input_format' => 'm-d H:i',
]);

Be trained by Symfony experts - 2019-02-25 Berlin - 2019-02-25 Berlin - 2019-02-25 Clichy
02/20/2019 06:10 am   Symfony Blog   Mirror   Link  

Coucou from Paris

The complete schedule for SymfonyLive Paris 2019 is online. Check out the last selected talks and speakers for the conference.


Le SymfonyLive Paris approche, rendez-vous les 28 et 29 mars 2019 à la Cité Internationale Universitaire de Paris.

Nous sommes ravis d'annoncer les derniers sujets sélectionnés au SymfonyLive Paris 2019 ! Nous avons pris le temps d'étudier toutes les propositions de sujet reçues lors du CFP pour le SymfonyLive Paris 2019 et nous remercions une nouvelle fois toutes les personnes qui ont soumis un sujet. Découvrez qui sont les derniers speakers retenus et les sujets qu'ils partageront avec vous durant la conférence :

  • Frédéric Bouchery fera une présentation sur "RabbitMQ simplement". RabbitMQ, vous en avez certainement entendu parler, mais franchement, ces histoires d'exchange, de queue, de binding, de topic, de fanout, ce n'est pas toujours très clair. Et de toutes façons, vous ne pensez pas trop en avoir besoin ! Lors de cette conférence, très didactique, vous découvrirez les bases de RabbitMQ et une sélection d'usages pragmatiques et directement utilisables dans vos projets de tous les jours. Bref, pas de bullshit : vous allez enfin comprendre comment utiliser RabbitMQ en PHP et votre monde va s'éclairer, promesse tenue !

  • Kevin Dejour et Philippe Vincent-Royol seront sur scène pour parler "Du développement à la production, une architecture grandissante". "Sur mon poste ça fonctionne bien pourtant !" Tout le monde est confronté à ce problème. Quelles sont les différentes étapes de la mise en place de l'architecture jusqu'à la configuration de Symfony ? Lors de cette conférence, nous verrons la mise en place et l’utilisation des mécanismes de caches (HTTP et Persitant) d’une simple installation mono serveur à une architecture sur 3 data centers.

  • Nicolas Grekas travaille depuis plusieurs mois sur un nouveau composant qui sera révélé lors de la Keynote de Fabien Potencier au SymfonyLive Lille 2019 le 1er mars. Son sujet lors du SymfonyLive Paris 2019 portera sur l'arrivée de ce nouveau composant, il vous expliquera en détails à quoi il va vous servir, comment il va simplifier vos développements et comment l'utiliser ! Le titre de son sujet sera annoncé après le SymfonyLive Lille 2019. Restez à l'écoute...

  • Grégoire Hébert détaillera la "Leçon N° 139, API Platform ce n'est bon qu'à faire un POC, FAUX !". La première chose qui est mise en avant avec API Platform c'est la capacité de faire du développement rapide d'application. Voyons ensemble les mécanismes avancés d'API Platform et les outils qui en feront votre framework API en PHP.

  • Chris Holland viendra des Etats-Unis pour nous présenter son sujet sur le "Développement d'applications TDD avec Symfony et ses amis en situation réelle". Il expliquera en détails comment démarrer Symfony avec REST, OAuth, la gestion des utilisateurs, les tests d'acceptation et les tests unitaires ainsi que la mise en place de Doctrine avec PHPUnit, pour permettre un workflow TDD hautement productif. Vous découvrirez également comment optimiser la performance sur les tests unitaires lors de l'introduction de ces frameworks et utiliser Codeception pour tester la création des Controller, avec des tests de bout en bout sur le serveur web, en utilisant votre MySQL local.

  • Mathieu Santostefano prendra la parole pour vous présenter une conférence sur "Des images au cordeau pour vos applications Symfony". Le responsive est une pratique largement répandue dans nos projets depuis quelques années maintenant. Mais lorsqu'il s'agit d'adapter les images, les techniques sont souvent moins connues, et parfois perçues comme expérimentales. Nous listerons ensemble quels sont les standards actuels permettant de charger la bonne image à la bonne taille et au bon format pour le bon terminal. Puis, nous verrons comment implémenter ces standards au sein d'une application Symfony, quels outils utiliser et comment tirer parti de Twig pour nous faciliter le travail !

Serez-vous là ? Prenez vite vos billets avant que le prix n'augmente, l'inscription à la conférence au tarif normal à 289€ est disponible jusqu'au 4 mars !

Vous souhaitez également assister aux formations ? Toutes nos formations sont éligibles au Fafiec, contactez-nous via le support pour votre inscription ! Sinon réservez votre combo formations-conférence directement en ligne. L'inscription aux formations concerne les 2 jours de formation des 26 et 27 mars, vous devez choisir une formation par jour au choix parmi :

  • Mardi 26 mars : Analyser les performances des applications Symfony ou Maîtriser le composant Workflow ou Maîtriser la POO & les Design Patterns
  • Mercredi 27 mars : Guide de bonnes pratiques Symfony 4 ou Développement d'API avec API Platform ou Symfony Messenger

Rendez-vous fin mars à Paris ou la semaine prochaine, le 1er mars, au SymfonyLive Lille ! A bientôt !


Be trained by Symfony experts - 2019-02-20 Clichy - 2019-02-25 Berlin - 2019-02-25 Berlin
02/19/2019 06:13 am   Symfony Blog   Mirror   Link  

SymfonyInsight helps you create maintainable and robust Symfony projects by giving you actionable metrics and hints about your project’s code.

However, while fixing actual code quality issues is definitely important, it is only a part of the problem. It does not deal with the other side of software quality: human organization. Designing a solution to a problem requires a deep and clear understanding of this problem, and the process in which this understanding happens is another potential source of quality improvement.

This is the reason why we are introducing the SymfonyInsight Portfolio.

Displaying the right information at the right time is key

SymfonyInsight shines at helping you tackle technical quality issues mainly because of a few key features:

  • it integrates smoothly in your daily work (commit statuses to Github/Bitbucket/Gitlab, e-mail/Slack notifications, …) ;
  • it works on your project’s code itself and is more focused on Symfony than other competitors (it boots your Symfony application to analyse its container, its Doctrine entities, etc.) ;
  • it displays aggregated analysis reports alongside your code, providing actionable metrics efficiently.

By focusing on the integration and the aggregation of information, SymfonyInsight is able to display to right information, concisely, right where you need it.

When we started to conceive a feature helping teams improve their projects' quality, we wanted to provide the same quality of concise information. This is exactly the aim of the Portfolio: a single dashboard showing the most important metrics about what is currently happening in your team’s projects, in real time.

SymfonyInsight Portfolio

The purpose of the Portfolio is to give teams the ability to monitor multiple projects efficiently, both in terms of size and in terms of quality, without having to follow all the pull requests and commits individually. It is designed to give a basis on which better communication about quality can happen.

The Portfolio focuses on the most important elements you need to know for each project:

  • the critical issues, including security problems, that need to be fixed as soon as possible ;
  • the total technical debt accumulated by your projects (the estimated time a single developer would need to fix all the issues detected by SymfonyInsight) ;
  • the size and the size evolution of your projects, in number of lines of code ;
  • the quality evolution over time, with a specific details about Performance, Maintainability, Security and Architecture.

It also creates a chart comparing the evolution of technical debt and project size over time, letting you know when you should probably invest on technical debt to avoid it to get out of control.

Interested in improving your projects quality? Go to insight.symfony.com to get started or read the Portfolio documentation to learn more!


Be trained by Symfony experts - 2019-02-18 Clichy - 2019-02-18 Clichy - 2019-02-20 Clichy
02/18/2019 03:51 am   Symfony Blog   Mirror   Link  

This week, a coordinated community effort updated the Symfony translation files for lots of languages (we're still looking for contributors for some European and Asian languages). Meanwhile, the upcoming Symfony 4.3 version added a JSON validator and improved the form translation.

Symfony development highlights

This week, 68 pull requests were merged (58 in code and 10 in docs) and 54 issues were closed (48 in code and 6 in docs). Excluding merges, 47 authors made 2,599 additions and 144 deletions. See details for code and docs.

3.4 changelog:

  • 6d881f7: fixed KernelTestCase compatibility for PhpUnit 8
  • d3d880a: [Security] fixed switch user without having current token
  • fd78757: [Form] forward valid numeric values to transform()
  • 0887f62: [FrameworkBundle] added constraint validators before optimizations
  • 5a15453: [Twig] removed usage of non-namespaced classes
  • dee2fcb: [Debug] preserved the next error handler
  • 650f712: [Validator] updated the French translation
  • f2370eb: [Validator] updated the Portuguese translation
  • 8d84cf9: [Validator] updated the Russian translation
  • 50f3ae5: [Validator] updated the Polish translation
  • 2382670: [Validator] updated the Italian translation
  • 558032b: [Validator] updated the Galician translation
  • 4974e0e: [Validator] updated the German translation
  • 0af5bd1: [Validator] updated the Arabic translation
  • b799c95: [Validator] updated the Welsh translation
  • de2301b: [Validator] updated the Hungarian translation
  • 59617ee: [Validator] updated the Spanish translation
  • 6e269cf: [Validator] updated the Turkish translation
  • 7548f9c: [Validator] updated the Indonesian translation
  • a9353c2: [Validator] updated the Dutch translation
  • a162669: [Validator] updated the Albanian translation
  • 491e87a: [Validator] updated the Persian translation
  • 3be75cc: [Validator] updated the Ukrainian translation
  • 45023ac: [Validator] updated the Catalan translation
  • 320c05f: [Validator] updated the Basque translation
  • 2f5b16f: [Validator] updated the Bulgarian translation
  • 8364fe4: [Validator] updated the Luxembourgish translation
  • de1f4c4: [Validator] updated the Lithuanian translation
  • d83c296: [Validator] updated the Romanian translation

Master changelog:

  • 3b8fa12: [FrameworkBundle] added support for PHP files with trans() in translation commands
  • 865127b: [SecurityBundle] deprecated the normalization of the cookie names
  • b9b8f9d: [FrameworkBundle] consolidated the MIME types service definition
  • 09275d4: [Form] added label_translation_parameters, help_translation_parameters and attr_translation_parameters options to base form type
  • b951a0f: [Validator] added new JSON Validator
  • c6a2c33: [Form] added a convenience method to get the parent form in Twig templates

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2019-02-18 Clichy - 2019-02-18 Clichy - 2019-02-20 Clichy
02/17/2019 03:17 am   Symfony Blog   Mirror   Link  

Contributed by
Anthony Martin
in #30027.

PHP defines lots of config options related to sessions. In Symfony we define them under the framework.session.* options so you don't have to change your PHP.ini to configure those values.

In Symfony 4.3 we added two new config options related to session IDs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# config/packages/framework.yaml
framework:
    session:
        # configures the length of the string used for the session ID
        # integer; default = 32; valid values = from 22 to 256 (both inclusive)
        sid_length: 64

        # configures the number of bits in encoded session ID character
        # integer; default = 4; valid values: 4, 5, or 6.
        sid_bits_per_character: 4

These new options are related to the session.sid_length PHP option and the session.sid_bits_per_character PHP option respectively, where you can find more details about them.


Be trained by Symfony experts - 2019-02-18 Clichy - 2019-02-18 Clichy - 2019-02-20 Clichy
02/15/2019 06:32 am   Symfony Blog   Mirror   Link  

Contributed by
Webnet team
in #28635.

The forms created with the Symfony Form component translate their labels and help messages automatically. However, the translations cannot contain any custom parameters because in the templates, the trans() Twig filter is called without passing any parameters.

In Symfony 4.3 we improved the translation of Symfony Forms allowing to define custom translation parameters using three new config options: label_translation_parameters, help_translation_parameters, and attr_translation_parameters (this one is useful to translate placeholder and title):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('comment', TextType::class, [
            'label' => 'Comment for the order of %company%',
            'label_translation_parameters' => [
                '%company%' => 'Acme Ltd.',
            ],

            'help' => 'The address of %company% is %address%',
            'help_translation_parameters' => [
                '%company%' => 'Acme Ltd.',
                '%address%' => '4 Form street, Symfonyville',
            ],
        ])
    }
}

Be trained by Symfony experts - 2019-02-18 Clichy - 2019-02-18 Clichy - 2019-02-20 Clichy
02/14/2019 05:03 am   Symfony Blog   Mirror   Link  

Contributed by
Imad Zairig
in #28477.

JSON is arguably the most used format in applications developed with Symfony. You probably make requests to JSON APIs and send/receive JSON payloads in your projects. That's why Symfony provides a JsonResponse class, a way to build JSON authentication, full JSON support in the Serializer component, a json() helper for controllers, etc.

In Symfony 4.3 we improved the Validator component to add a new Json constraint, which can be applied to properties and getters, and ensures that the given contents are valid JSON contents:

  • Annotations
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    // src/Entity/Book.php
    namespace App\Entity;
    
    use Symfony\Component\Validator\Constraints as Assert;
    
    class Book
    {
        /**
         * @Assert\Json(message = "This is not valid JSON")
         */
         protected $chapters;
    }
    
  • YAML
    1
    2
    3
    4
    5
    6
    # config/validator/validation.yaml
    App\Entity\Book:
        properties:
            chapters:
                - Json:
                    message: 'This is not valid JSON'
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    <!-- config/validator/validation.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
        <class name="App\Entity\Book">
             <property name="chapters">
                <constraint name="Json">
                    <option name="message">This is not valid JSON</option>
                </constraint>
            </property>
        </class>
    </constraint-mapping>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    // src/Entity/Book.php
    namespace App\Entity;
    
    use Symfony\Component\Validator\Mapping\ClassMetadata;
    use Symfony\Component\Validator\Constraints as Assert;
    
    class Book
    {
        protected $chapters;
    
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addPropertyConstraint('chapters', new Assert\Json(array(
                'message' => 'This is not valid JSON',
            )));
        }
    }
    

Be trained by Symfony experts - 2019-02-18 Clichy - 2019-02-18 Clichy - 2019-02-20 Clichy
02/13/2019 04:36 am   Symfony Blog   Mirror   Link  

Contributed by
Christian Flothmann
in #29999.

The PropertyAccess component allows to read/write properties from objects and arrays using a simple string notation. It's used by Symfony components like Forms, Security, Validator, Workflow and hundreds of other public projects.

In Symfony 4.3 we improved its performance refactoring the code of the ObjectNormalizer class. The trick was to add some shortcuts for cases where we know that we do not need to perform all checks.

Saving so many function calls in such a critical operation results in a 20% to 30% performance improvement for a non-trivial synthetic benchmark. You can expect even better improvements if your app deals with large objects and complex property paths.

Best of all? You don't need to make any change in your application code to benefit from this improvement. Upgrade to Symfony 4.3 when it's released at the end of May 2019 and that's all.


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/08/2019 09:30 am   Symfony Blog   Mirror   Link  

SymfonyLive Tunis 2019 Conference Logo

Register now or submit a talk proposal for SymfonyLive Tunis 2019, the first SymfonyLive conference organized in Tunisia. The entire event will be organized in French.


Nous sommes ravis d'organiser la première édition de la conférence SymfonyLive à Tunis !

La conférence aura lieu le samedi 27 avril au Mövenpick Hotel du Lac à Tunis. Nous vous donnons rendez-vous pour une journée entière de partage de connaissances sur Symfony, PHP et de rencontres avec l’écosystème local de Symfony réunis autour d’un track ! Deux journées de formation sont également organisées les jeudi 25 et vendredi 26 avril. Vous pouvez choisir les formations suivantes et créer votre propre agenda de formations.

Jeudi 25 avril 2019, les formations proposées sont :

  • Guide de bonnes pratiques Symfony 4 par Nicolas Grekas - Symfony SAS
  • Maîtriser la POO & les Design Patterns par Titouan Galopin - SymfonyInsight lead

Vendredi 26 avril 2019, les formations proposées sont :

  • Analyser les performances des applications Symfony par Nicolas Grekas - Symfony SAS
  • Développement d'API avec API Platform par Kévin Dunglas - Les-Tilleuls.coop

Le Call for Papers est ouvert jusqu'au 11 mars 2019. Vous pouvez dès à présent envoyer vos propositions de sujet pour devenir speaker de la conférence SymfonyLive Tunis 2019. Parlez-nous de Symfony, PHP, de vos retours d'expérience, de vos bonnes pratiques ou d'autres sujets en relation avec Symfony. N'hésitez pas à envoyer plusieurs propositions de sujet pour augmenter vos chances de sélection et à les détailler au maximum ! Si vous n'avez jamais été speaker à une conférence auparavant, nous avons un programme de mentoring pour speakers, nous serons ravis de vous aider à travailler vos slides, répéter votre conférence... N'hésitez pas à nous signaler si vous souhaitez être aidé lors de votre soumission de sujet pour la conférence.

Les inscriptions à la conférence sont ouvertes, le billet pour participer à la conférence coûte 15€ HT et le combo formations et conférence coûte 460€ HT. Le paiement en devise locale (Dinar tunisien) sera prochainement disponible en ligne. Nous vous tiendrons informé dès qu'il sera effectif.

Inscrivez-vous dès maintenant à la 1ère conférence SymfonyLive en Tunisie, nous vous donnons rendez-vous sous le soleil tunisien le 27 avril 2019 ! La conférence et les formations seront organisées en français.

Enfin, nous souhaitons remercier chaleureusement Adala Khaled pour son implication dans l'organisation des premières conférences Symfony TN il y a quelques années et pour son aide dans l'organisation de cette 1ère conférence SymfonyLive à Tunis. Un grand merci également à Pascal Borreli pour son soutien dans l'organisation de l'événement.

Si votre entreprise souhaite soutenir l'événement, n'hésitez pas à prendre contact avec nous pour devenir sponsor de l'événement.

Nous avons hâte de vous retrouver à Tunis !


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/07/2019 04:31 am   Symfony Blog   Mirror   Link  

Contributed by
Jérôme Vasseur
in #29753.

The common workflow for Symfony Console progress bars is to start them, advance them according to your task progress and finish them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use Symfony\Component\Console\Helper\ProgressBar;

$progressBar = new ProgressBar($output);
$progressBar->start();

// ... do some work
$progressBar->advance();

// needed to ensure that the bar reaches 100%
$progressBar->finish();

In Symfony 4.3 we've improved this workflow when you work with iterable variables (such as arrays or generators). Thanks to the new iterate() method, you can pass the iterable variable and the progress bar starts, advances and finishes automatically.

Consider the following simple PHP generator:

1
2
3
4
5
$iterable = function () {
    yield 1;
    yield 2;
    // ...
};

You can turn this into a progress bar as follows:

1
2
3
4
5
6
7
use Symfony\Component\Console\Helper\ProgressBar;

$progressBar = new ProgressBar($output);

foreach ($progressBar->iterate($iterable) as $value) {
    // ... do some work
}

The output in your terminal will be the following:

1
2
3
0 [>---------------------------]
1 [==============>-------------]
2 [============================]

If the iterable variable is countable, the max steps of the progress bar is set automatically. Otherwise, you can pass the number of steps as the second optional argument of iterate():

1
2
3
foreach ($progressBar->iterate($iterable, 100) as $value) {
    // ... do some work
}

Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/06/2019 02:36 am   Symfony Blog   Mirror   Link  

Symfony 4.2.3 has just been released. Here is a list of the most important changes:

  • bug #30050 [Cache] fix pruning pdo cache for vendors that throw on execute (@bendavies)
  • bug #30046 [DI] Fix dumping Doctrine-like service graphs (@nicolas-grekas)
  • bug #30028 [Form] fix some docblocks and type checks (@xabbuh)
  • bug #30037 Disable Twig in the profiler menu when Twig is not used (@javiereguiluz)
  • bug #30026 [VarDumper] dont implement Serializable in Stub (@nicolas-grekas)
  • bug #30034 [Config] ensure moving away from Serializable wont break cache:clear (@nicolas-grekas)
  • bug #29532 [Messenger] fixed RabbitMQ arguments not passed as integer values (@thePanz)
  • bug #30013 [Routing] dont redirect routes with greedy trailing vars with no explicit slash (@nicolas-grekas)
  • bug #30006 [Security] don't do nested calls to serialize() (@nicolas-grekas, @Renan)
  • bug #30007 [FrameworkBundle] Support use of hyphen in asset package name (@damaya, @XuruDragon)
  • bug #30004 Fix format strings for deprecation notices (@TysonAndre)
  • bug #29984 [VarDumper] Fixed search bar (@ro0NL)
  • bug #29764 [HttpFoundation] Check file exists before unlink (@adam-mospan)
  • bug #29783 [HttpFoundation] MemcachedSessionHandler::close() must close connection (@grachevko)
  • bug #29794 Always pass $key to NullAdapter->createCacheItem (@TysonAndre)
  • bug #29844 [Console] Fixed #29835: ConfirmationQuestion with default true for answer '0' (@mrthehud)
  • bug #29869 [Debug][ErrorHandler] Preserve our error handler when a logger sets another one (@fancyweb)
  • bug #29900 [Cache] PDO-based cache pool table autocreation does not work (@errogaht)
  • bug #29926 [Form] Changed UrlType input type to text when defaul _protocol is not null (@MatTheCat)
  • bug #29961 [Translation] Concatenated translation messages (@Stadly)
  • bug #29847 [Cache] fix used variable name (@xabbuh)
  • bug #29920 [Debug][DebugClassLoader] Match more cases for final, deprecated and internal classes / methods extends (@fancyweb)
  • bug #29922 Avoid dots in generated class names (@derrabus)
  • bug #29863 [Security] Do not mix passwor _() API with libsodium one (@chalasr)
  • bug #29894 [DependencyInjection] the string "0" is a valid service identifier (@xabbuh)
  • bug #29885 Update MimeType extensions (@fabpot)
  • bug #29875 [TwigBridge] fix compatibility with Twig >= 2.6.1 (@xabbuh)
  • bug #29873 [Debug] remove return type hint for PHP 5 compatibility (@xabbuh)
  • bug #29837 Fix SwiftMailerHandler to support Monolog's latest reset functionality (@Seldaek)
  • bug #29853 Revert "bug #29597 [DI] fix reporting bindings on overriden services as unused" (@mmarynich)
  • bug #29833 [DebugClassLoader] expose proxyfied findFile() method (@fancyweb)

Want to upgrade to this new release? Fortunately, because Symfony protects backwards-compatibility very closely, this should be quite easy. Read our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/03/2019 06:52 am   Symfony Blog   Mirror   Link  

Symfony 3.4.22 has just been released. Here is a list of the most important changes:

  • bug #30046 [DI] Fix dumping Doctrine-like service graphs (@nicolas-grekas)
  • bug #30028 [Form] fix some docblocks and type checks (@xabbuh)
  • bug #30037 Disable Twig in the profiler menu when Twig is not used (@javiereguiluz)
  • bug #30026 [VarDumper] dont implement Serializable in Stub (@nicolas-grekas)
  • bug #30034 [Config] ensure moving away from Serializable wont break cache:clear (@nicolas-grekas)
  • bug #30006 [Security] don't do nested calls to serialize() (@nicolas-grekas, @Renan)
  • bug #30007 [FrameworkBundle] Support use of hyphen in asset package name (@damaya, @XuruDragon)
  • bug #29764 [HttpFoundation] Check file exists before unlink (@adam-mospan)
  • bug #29783 [HttpFoundation] MemcachedSessionHandler::close() must close connection (@grachevko)
  • bug #29844 [Console] Fixed #29835: ConfirmationQuestion with default true for answer '0' (@mrthehud)
  • bug #29869 [Debug][ErrorHandler] Preserve our error handler when a logger sets another one (@fancyweb)
  • bug #29926 [Form] Changed UrlType input type to text when defaul _protocol is not null (@MatTheCat)
  • bug #29961 [Translation] Concatenated translation messages (@Stadly)
  • bug #29920 [Debug][DebugClassLoader] Match more cases for final, deprecated and internal classes / methods extends (@fancyweb)
  • bug #29863 [Security] Do not mix passwor _() API with libsodium one (@chalasr)
  • bug #29894 [DependencyInjection] the string "0" is a valid service identifier (@xabbuh)
  • bug #29885 Update MimeType extensions (@fabpot)
  • bug #29875 [TwigBridge] fix compatibility with Twig >= 2.6.1 (@xabbuh)
  • bug #29873 [Debug] remove return type hint for PHP 5 compatibility (@xabbuh)
  • bug #29837 Fix SwiftMailerHandler to support Monolog's latest reset functionality (@Seldaek)
  • bug #29853 Revert "bug #29597 [DI] fix reporting bindings on overriden services as unused" (@mmarynich)
  • bug #29833 [DebugClassLoader] expose proxyfied findFile() method (@fancyweb)

Want to upgrade to this new release? Fortunately, because Symfony protects backwards-compatibility very closely, this should be quite easy. Read our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/03/2019 06:47 am   Symfony Blog   Mirror   Link  

This week, Symfony 4.1.11 was released, marking the end of regular releases for the 4.1 branch. In addition, the Symfony Security Bug Bounty started this week. Lastly, the first speakers of SymfonyLive Paris 2019 conference were announced.

Symfony development highlights

This week, 48 pull requests were merged (34 in code and 14 in docs) and 43 issues were closed (42 in code and 1 in docs). Excluding merges, 28 authors made 1,153 additions and 530 deletions. See details for code and docs.

3.4 changelog:

  • c95fdbd: [FrameworkBundle] added support for using hyphens in asset package name
  • b4357d7: [Security] don't do nested calls to serialize()
  • c7937c9: [Config] ensure moving away from Serializable wont break cache:clear
  • 591c805: [VarDumper] don't implement Serializable in Stub
  • fb43484: [WebProfilerBundle] disable Twig in the profiler menu when Twig is not used
  • 11dc73d: [Security] fixed serialization workaround in CustomUserMessageAuthenticationException
  • 5b1948e: [DependencyInjection] fixed dumping Doctrine-like service graphs

4.1 changelog:

  • 05071a4: [Routing] don't redirect routes with greedy trailing vars with no explicit slash

4.2 changelog:

  • 50a0bda: [Messenger] fixed RabbitMQ arguments not passed as integer values
  • 4e4ebde: [Cache] fixed pruning pdo cache for vendors that throw on execute

Master changelog:

  • 5a8c06e: [Mime] moved the add mime type guesser pass to the component
  • dca0975: [DependencyInjection] added id of referencing service when a deprecated alias is found
  • be5d85e: [Validator] add a new option to allow null values in NotBlank
  • 0c6fd86: [Console] made "warning" in SymfonyStyle use orange color
  • b324445: [PropertyAccess] speed up accessing object properties
  • 9429fac: [Console] added an iterate method to the ProgressBar class
  • bd123e4: [DependencyInjection] fixed serialization of \Closure in RemoveUnusedDefinitionsPass

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/03/2019 05:02 am   Symfony Blog   Mirror   Link  

Contributed by
Kévin Dunglas
in #29641.

The NotBlank constraint of the Validator component checks that a value is not false, null, an empty array or an empty string. Most of the other constraints ignore null values, but NotBlank validates them. This causes issues in scenarios such as APIs called from front-end code, where is easier to include null fields instead of removing those fields when making requests.

In Symfony 4.3 we've improved the NotBlank constraint adding a new allowNull option to it. By default this option is false, to keep the current behavior. If you set it to true, then null values will be considered valid instead of triggering a constraint violation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class SomeEntity
{
    /**
     * @Assert\NotBlank(allowNull = true)
     */
    protected $someProperty;
}

Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
02/01/2019 03:21 am   Symfony Blog   Mirror   Link  

Symfony 4.1.11 has just been released. Here is a list of the most important changes:

  • bug #30013 [Routing] dont redirect routes with greedy trailing vars with no explicit slash (@nicolas-grekas)
  • bug #30006 [Security] don't do nested calls to serialize() (@nicolas-grekas, @Renan)
  • bug #30007 [FrameworkBundle] Support use of hyphen in asset package name (@damaya, @XuruDragon)
  • bug #29764 [HttpFoundation] Check file exists before unlink (@adam-mospan)
  • bug #29783 [HttpFoundation] MemcachedSessionHandler::close() must close connection (@grachevko)
  • bug #29844 [Console] Fixed #29835: ConfirmationQuestion with default true for answer '0' (@mrthehud)
  • bug #29869 [Debug][ErrorHandler] Preserve our error handler when a logger sets another one (@fancyweb)
  • bug #29926 [Form] Changed UrlType input type to text when defaul _protocol is not null (@MatTheCat)
  • bug #29961 [Translation] Concatenated translation messages (@Stadly)
  • bug #29920 [Debug][DebugClassLoader] Match more cases for final, deprecated and internal classes / methods extends (@fancyweb)
  • bug #29863 [Security] Do not mix passwor _() API with libsodium one (@chalasr)
  • bug #29894 [DependencyInjection] the string "0" is a valid service identifier (@xabbuh)
  • bug #29885 Update MimeType extensions (@fabpot)
  • bug #29875 [TwigBridge] fix compatibility with Twig >= 2.6.1 (@xabbuh)
  • bug #29873 [Debug] remove return type hint for PHP 5 compatibility (@xabbuh)
  • bug #29837 Fix SwiftMailerHandler to support Monolog's latest reset functionality (@Seldaek)
  • bug #29853 Revert "bug #29597 [DI] fix reporting bindings on overriden services as unused" (@mmarynich)
  • bug #29833 [DebugClassLoader] expose proxyfied findFile() method (@fancyweb)

Want to upgrade to this new release? Fortunately, because Symfony protects backwards-compatibility very closely, this should be quite easy. Read our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
01/29/2019 09:34 am   Symfony Blog   Mirror   Link  

We've selected the first talks for SymfonyLive Paris 2019, a huge thank you to all the people who submitted a talk proposal for the conference!


La première partie du programme du SymfonyLive Paris 2019 est disponible !

Le SymfonyLive Paris 2019 aura lieu dans 2 mois, les 28 et 29 mars 2019 à la Cité Internationale Universitaire de Paris !

Tout d’abord nous voulons remercier toutes les personnes qui ont pris le temps de soumettre un ou plusieurs sujets lors de notre Call for Papers pour le SymfonyLive Paris 2019. Nous avons reçu de nombreux très bons sujets et la sélection des sujets n’a pas été simple mais nous sommes heureux d'annoncer les premiers sujets sélectionnés pour l’édition 2019 du SymfonyLive Paris :

  • Damien Alexandre viendra présenter une conférence intitulée " État de l'art d'Elasticsearch avec Symfony ". Tout le monde utilise Elasticsearch, mais qui en comprend vraiment les particularités ? Dans ce talk il vous exposera ses recommandations sur la mise en place du moteur de recherche dans un applicatif Web et les pièges dans lesquels nous tombons le plus souvent.
  • Romaric Drigon parlera de " Doctrine en dehors des sentiers battus ". L'ORM Doctrine offre beaucoup plus de flexibilité qu'il n'y paraît. Dans cette présentation, nous allons nous intéresser à son fonctionnement interne et à ses fonctionnalités moins connues, pour découvrir comment mieux l'utiliser.
  • Kévin Dunglas livrera ses bonnes pratiques au travers de son sujet " Améliorez progressivement vos applications Symfony 4 ". Symfony 4 contient de nombreux outils rendant très facile d'intégrer les outils JS moderne dans le framework. Au cours de ce talk nous découvrirons comment utiliser ensembles VueJS (l'un des frameworks les plus populaires en JavaScript), API Platform (l'outil de référence pour la création d'API web modernes), Panther (l'outil de test E2E de Symfony qui est capable d'exécuter le JavaScript afin de progressivement améliorer nos applications grâce à JavaScript.
  • Benoit Jacquemont vous expliquera tout ce qu'il y a à savoir sur " HTTP/3: C'est une question de transport ! ". L'annonce de HTTP/3 au début de novembre 2018 en a surpris plus d'un: moins de 4 ans la sépare de HTTP/2, alors que 8 s'était écoulé entre HTTP/1.1 et HTTP/2. Néanmoins cette version apporte une vraie complémentarité au travail réalisé sur HTTP/2, notamment sur les problématiques de latence. Ce talk reviendra sur le pourquoi de cette version 3, ce qu'elle apporte et ce qu'elle change, et ce que peuvent en attendre les développeurs web.
  • Danielle Kayumbi Bonkoto vous présentera " Les meilleurs bundles et outils pour vos applications Symfony ". Il existe un large choix de bundles et d'outils permettant de d'implémenter rapidement un besoin fonctionnel ou technique. Cependant, certains bundles sont plus souples, plus rapides et plus simples à prendre en main, ce qui permet de gagner en temps dans le développement d'une feature. Découvrez la liste des meilleurs bundles et outils pour vos applications Symfony !
  • Fabien Potencier sera sur scène pour la Keynote d'ouverture le jeudi 28 mars à 9h15 !
  • Kevin Verschaeve vous donnera son " Top 5 des raisons d'utiliser le serveur web local de Symfony. La 6e va vous étonner ! ". Découvrez toutes les raisons d'utiliser le serveur web de la nouvelle ligne de commande Symfony.
  • Jérôme Vieilledent sera sur scène pour la Keynote du vendredi 29 mars à 9h avec une conférence sur l' " Open source, renouveau de l'Humanisme ".
  • François Zaninotto vous proposera de partir en " Voyage au coeur de React-admin, l'admin generator d'API Platform ". API Platform fournit en standard un admin generator très sophistiqué, mais assez déroutant pour les développeurs PHP, puisqu'il est en JavaScript. Au cours de cette session, prenez le risque de passer du côté obscur et découvrez les secrets de react-admin.

Découvrez dès maintenant le programme de la conférence et les sujets sélectionnés en détails. Nous voulons adresser un immense merci à tous ceux qui ont soumis un sujet !

La conférence SymfonyLive Paris c'est aussi 2 journées de formations les 26 et 27 mars organisées en amont de la conférence. Vous pouvez acheter un combo formations et conférence et choisir vous-même vos formations. Nous proposons des formations sur une journée, 3 formations différentes sont proposées par jour pour que vous puissiez créer votre combo personnel. Cette année, nous vous proposons les formations suivantes :

Le mardi 26 mars au choix :

  • Analyser les performances des applications Symfony par Nicolas Grekas - Symfony SAS
  • Maîtriser le composant Workflow par Jules Pietri - SensioLabs
  • Maîtriser la POO & les Design Patterns par Titouan Galopin - SymfonyInsight lead

Le mercredi 27 mars au choix :

  • Guide de bonnes pratiques Symfony 4 par Nicolas Grekas - Symfony SAS
  • Développement d'API avec API Platform par Kévin Dunglas - Les-Tilleuls.coop
  • Symfony Messenger par Thibault Henry - Expert du composant

Réservez vite vos billets pour assister à la conférence ou aux formations et à la conférence et rendez-vous dans 2 mois !


Be trained by Symfony experts - 2019-02-11 Clichy - 2019-02-11 Clichy - 2019-02-13 Clichy
01/28/2019 09:30 am   Symfony Blog   Mirror   Link  

This week Symfony focused on fixing the last issues found in the upcoming Symfony 4.2 version, which will be released in two weeks. We also improved the way to handle .env files in Symfony apps. Lastly, we announced discounts to save up to 30% in some Symfony services and a new SymfonyLive conference in Lille (France) in 2019.

Symfony development highlights

This week, 21 pull requests were merged (18 in code and 3 in docs) and 20 issues were closed. Excluding merges, 16 authors made 565 additions and 202 deletions. See details for code and docs.

2.8 changelog:

  • e4a7fd8: [HttpFoundation] fixed trailing space for mime-type with parameters

3.4 changelog:

  • b74a086: [FrameworkBundle] deal with explicitly enabled workflow nodes
  • e166d96: [PhpUnit Bridge] used Composer to download phpunit
  • d0698b2: [Form] fixed empty data for compound date interval
  • 73d9804: [DependencyInjection] fixed taking lazy services into account when dumping the container
  • ab51fa8: [Cache] fixed optimizing Psr6Cache for AdapterInterface pools
  • 812a878: [Routing] removed duplicate schemes and methods for invokable controllers
  • 0f2d577: [HttpFoundation] fixed absolute Request URI with default port
  • 7f310b4: [Dotenv] properly parse backslashes in unquoted env vars

Master changelog:

  • 227cf2c: [Messenger] added a trait for synchronous query & command buses
  • 4c1e8bd: [HttpKernel, WebProfilerBundle] get the cached client mime type instead of guessing it again
  • f9414a8: [Lock] fixed PdoStore::putOffExpiration() and PdoStore::getHashedKey()

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/25/2018 02:54 am   Symfony Blog   Mirror   Link  

It’s the most wonderful time of the year: Black Friday deals! This year we’re super happy to offer you 4 great deals from the Symfony ecosystem to enhance your developer experience and web projects development:

For the first time ever on SymfonyCasts, get a one-time 40% discount off your new subscription or next renewal - using code BF2018. Get (or upgrade to) an annual subscription for max benefit! SymfonyCasts is the official video tutorial site for Symfony and the best way to learn it! Access to 90+ hours of video content to improve your Symfony skills. And, this is Ryan Weaver - Symfony Core Team member and documentation lead- who will teach you all about Symfony in videos. Subscribe now, the offer is only available for 2 days!

This year again, you can enjoy our Black Friday offer on all certifications! Buy your Symfony discounted certification voucher at 175€ instead of the regular 250€ or your Twig discounted certification voucher at 104,3€ instead of the regular 149€ and take the exam when you’re ready. You have a year from your date of purchase to take the exam. If you’re not ready yet to take the certification, you can buy it and get trained until you’re ready to take it and pass it. Plus since October 2018, it’s an online exam so it’s easier than ever to schedule your exam. Save money now and become certified from home!

Pick any yearly Business plans and start monitoring your projects' quality today with SymfonyInsight. The discounted Business Pro plan is now at 56€/month instead of 79€ and the discounted Business Enterprise plan at 98€/month instead of 139€. SymfonyInsight continuously analyzes your code to detect security risks, find bugs, provide actionable metrics and helps improve your projects in the long term through 100+ checks and guidelines. Enjoy our Black Friday offer, choose SymfonyInsight now for your PHP project quality!

Use the BlackFriday18 coupon to get a 20% discount on new yearly Premium and Enterprise subscriptions. Performance isn’t something you should care about once in a while and it’s even more relevant for the Black Friday/Cyber Monday period, when your eCommerce sites will be put under stress. Just try a quick Google search. It’s the same every year; even major brands get some downtime due to performance issues. Adopt now Blackfire to automate performance testing!

Don’t wait to buy your Black Friday offers, they won’t last for long!


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/22/2018 07:37 am   Symfony Blog   Mirror   Link  

SymfonyLive Lille 2019 Conference Logo

We’re very pleased to inform you that we’ll organize for the first time ever a new conference in France! On top of the SymfonyLive Paris 2019, March 28-29, we’ll meet you next year in the great capital of Hauts de France region. Let’s meet in Lille on March 1st for a one-day conference about Symfony, PHP, their ecosystems… The conference will be a one-track event organized at the Auberge Stephane Hessel. We’d like to gather the Symfony community from the Hauts de France region and meet you in the dynamic city of Lille.

The Call for Papers is already open, you can already submit your talk proposals for the conference. The CFP is open until December 31st included.

The day before the conference on Thursday February 28th will be the usual pre-conference workshops day. The workshop topics will be soon announced. The combo tickets will be soon on sale at the unique price of 495€ (VAT excluded) for the 2-day pack (workshop and conference).

But you can already register to the conference at the unique price of 159€ (VAT excluded). Attention, we have a limited number of conference tickets on sale to 130 tickets, first come, first served!

We’re looking forward to welcome you at SymfonyLive Lille. See you on March 1st 2019!


La conférence SymfonyLive s’installe à Lille !

Nous sommes très heureux de vous annoncer que pour la première fois, nous allons organiser une nouvelle conférence SymfonyLive en France. En plus de la conférence de Paris des 28 et 29 mars 2019***, nous vous donnons rendez-vous l’an prochain dans la très belle capitale des Hauts de France ! **Retrouvez nous à Lille le vendredi 1er mars pour une journée de conférences sur Symfony, PHP, leurs écosystèmes… La conférence aura lieu à l’Auberge Stephane Hessel au cœur de la ville. Nous souhaitons rassembler la communauté Symfony de la région des Hauts de France et venir à votre rencontre dans la dynamique métropole lilloise.

Le Call for Papers est déjà ouvert, vous pouvez soumettre vos propositions de sujet pour la conférence dès maintenant. Le CFP est ouvert jusqu’au 31 décembre inclus.

Nous organisons la veille de la conférence, le jeudi 28 février, des formations pré-conférence, les sujets des formations seront bientôt annoncés. Les billets combo seront également bientôt en vente au tarif unique de 495€ HT le pack 2 jours (formations et conférence).

En attendant vous pouvez déjà vous inscrire à la conférence au tarif unique de 159€ HT. Attention, le nombre de places à la conférence est limité à 130 personnes, premiers inscrits, premiers servis !

Nous avons hâte de vous retrouver au SymfonyLive Lille 2019 quoi ! On se retrouve le 1er mars les biloutes !


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/19/2018 09:33 am   Symfony Blog   Mirror   Link  

When Symfony 4.0 was released, the .env file was introduced as a way to set environment variables. The core of the system has not changed. But, thanks to recent updates to some core Symfony recipes, .env loading has some new features that can be enjoyed on any Symfony Flex project!

If you have an existing Symfony app (started before today), your app does not require any changes to keep working. But, if/when you are ready to take advantage of these improvements, you will need to make a few small updates.

What Changed Exactly?

But first, what changed? On a high-level, not much. Here's a summary of the most important changes:

  • A) The .env.dist file no longer exists. Its contents should be moved to your .env file (see the next point).
  • B) The .env file is now committed to your repository. It was previously ignored via the .gitignore file (the updated recipe does not ignore this file). Because this file is committed, it should contain non-sensitive, default values. Basically, the .env.dist file was moved to .env.
  • C) A .env.local file can now be created to override environment variables for your machine. This file is ignored in the new .gitignore.
  • D) When testing, your .env file is now read, making it consistent with all other environments. You can also create a .env.test file for test-environment overrides.

Point (D) is one of the main motivations behind these changes: it makes setting and overriding environment variables for your test environment a delight.

These improvements can be used in any Symfony Flex project (Symfony 3.4 or higher). Changes to the recipes (see below) make it possible to take advantage of the Symfony 4.2 feature - Define env vars per environment - in lower versions.

To take advantage of these, you will need to modify a few files in your existing app.

Updating My Application

Updating your existing application is optional, but just requires modifying a few files. To update, see: DotEnv: Update my Application in the Symfony Docs.

Bonus: --env & --no-debug Console Deprecations Removed

The --env and --no-debug were recently deprecated. However, based on community feedback and work on these new .env features, the deprecation has been reverted: the --env and --no-debug options will continue to work! And, the proper .env files will be loaded. For example, want to create the schema in your test environment using a customized DATABASE_URL in your .env.test file? That will work just like you expect:

1
$ php bin/console doctrine:schema:create --env=test

Have any questions? Let us know!

❤️ The Symfony Community


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/19/2018 08:04 am   Symfony Blog   Mirror   Link  

This week, the second beta of Symfony 4.2 was published in preparation for its final release in two weeks. In order to simplify the maintenance of Symfony apps, we undeprecated the single-colon controller notation and also reverted the deprecation of --env and --no-debug console options.

Symfony development highlights

This week, 54 pull requests were merged (38 in code and 16 in docs) and 64 issues were closed (48 in code and 16 in docs). Excluding merges, 32 authors made 2,656 additions and 914 deletions. See details for code and docs.

2.8 changelog:

  • 26f321c: [Config] unset key during normalization
  • 893237d: [Form] invalidated forms on transformation failures
  • 32c0172: [Form] fixed keeping hash of equal \DateTimeInterface on submit
  • f975be2: [Form] fixed empty data for compound date types
  • b11ec05: [Validator] added the missing constraints instance checks

3.4 changelog:

  • 8dcefc9: [Workflow] fixed guard event names for transitions
  • 1ac042b: [PropertyAccessor] fixed unable to write to singular property using setter while plural adder/remover exist
  • 236565c: [DependencyInjection] don't fail on missing classes when resource tracking is disabled

4.1 changelog:

  • 28cd88e: [Workflow] fixed bug of buildTransitionBlockerList when many transition are enabled
  • c96325f: [Routing] generate(null) should throw an exception
  • e59e4e0: undeprecated the single-colon controller notation

Master changelog:

  • fb249f0: [Messenger] collect all stamps added on Envelope as collections
  • 3778585: [HttpKernel] fixed collecting uploaded files
  • 443f8ad: [FrameworkBundle] reverted deprecation of --env and --no-debug console options
  • 100f205: [VarExporter] fixed handling of __sleep()
  • 88891d5: [Messenger] added handled & sent stamps
  • ef75454: [Translation] made intl+icu format seamless by handling it in MessageCatalogue
  • f975be2: [Form] fixed empty data for compound date types
  • 429f500: [Debug] removed frames added by DebugClassLoader in stack traces

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/18/2018 04:20 am   Symfony Blog   Mirror   Link  

Contributed by
Roland Franssen
in #24263 and #28934.

Symfony Profiler provides detailed debug information about your applications. Sometimes it provides so much information that it may be overwhelming. That's why in Symfony 4.2 we've improved the log panel adding filters so you can see only the log messages you are interested in:

Filters are added to the log level and the log channel. They are created dynamically with JavaScript, so you can filter by your own custom channels too:


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/16/2018 09:45 am   Symfony Blog   Mirror   Link  

Symfony 4.2.0-BETA2 has just been released. Here is a list of the most important changes:

  • bug #29190 [Debug][HttpKernel] remove frames added by DebugClassLoader in stack traces (@nicolas-grekas)
  • bug #29233 [FrameworkBundle] metadat _updat _threshold default value must be an int (@dunglas)
  • bug #29226 [Messenger] Improved message when handler class does not exist (@neeckeloo)
  • bug #29223 [Validator] Added the missing constraints instance checks (@thomasbisignani)
  • bug #28966 [PropertyAccessor] Fix unable to write to singular property using setter while plural adder/remover exist (@karser)
  • bug #29182 [Form] Fixed empty data for compound date types (@HeahDude)
  • bug #29224 [SecurityBundle] Fix remember-me cookie framework inheritance when session is disabled (@fbourigault)
  • bug #29220 [Translation] make intl+icu format seamless by handling it in MessageCatalogue (@nicolas-grekas)
  • feature #29166 [Messenger] Add handled & sent stamps (@ogizanagi)
  • bug #29209 [VarExporter] fix handling of sleep() (@nicolas-grekas)
  • bug #29196 [Messenger] Fix collecting messages (@ro0NL)
  • bug #29205 [Dotenv] skip loading "local" env twice (@nicolas-grekas)
  • bug #29204 [FrameworkBundle][WebServerBundle] Revert deprecation of --env and --no-debug console options (@chalasr)
  • bug #29191 [Routing] generate(null) should throw an exception (@nicolas-grekas)
  • bug #29199 [FrameworkBundle] conflict with Dotenv <4.2 to simplify recipes (@nicolas-grekas)
  • bug #29197 Revert "bug #29154 [FrameworkBundle] Define AP _ENV/AP _DEBUG from argv via Application::bootstrapEnv() (@nicolas-grekas)
  • bug #29185 [Form] Fixed keeping hash of equal DateTimeInterface on submit (@HeahDude)
  • bug #29183 [HttpKernel] Fix collecting uploaded files (@ro0NL)
  • bug #29141 [Workflow] Fixed bug of buildTransitionBlockerList when many transition are enabled (@Tetragramat, @lyrixx)
  • bug #29137 [Workflow][FrameworkBundle] fixed guard event names for transitions (@destillat, @lyrixx)
  • bug #29184 [WebProfilerBundle] Fix theme settings (@ro0NL)
  • feature #29159 [Messenger] collect all stamps added on Envelope as collections (@nicolas-grekas)
  • bug #29171 [Dotenv] load .env.dist when it exists and .env is not found (@nicolas-grekas)
  • bug #28731 [Form] invalidate forms on transformation failures (@xabbuh)
  • bug #29152 [Config] Unset key during normalization (@ro0NL)
  • bug #29165 [DI] align IniFileLoader to PHP bugfix #76965 (@nicolas-grekas)
  • bug #29154 [FrameworkBundle] Define AP _ENV/AP _DEBUG from argv via Application::bootstrapEnv() (@chalasr)
  • bug #29129 [Dotenv] add loadEnv(), a smoother alternative to loadForEnv() (@nicolas-grekas)
  • bug #29113 [Routing] fix dumping conditions that use the request (@nicolas-grekas)
  • bug #29115 Change butto _widget class to btn-primary (@neFAST)
  • bug #29131 [Dotenv] dont use getenv() to read SYMFON _DOTEN _VARS (@nicolas-grekas)
  • bug #29057 [HttpFoundation] replace any preexisting Content-Type headers (@nicolas-grekas)
  • bug #29076 [Serializer] Allow null values when denormalizing with constructor missing data (@danut007ro)
  • bug #29128 [FrameworkBundle] Cleaning translation commands and fix a bug for --all option (@yceruto)
  • bug #29104 [DI] fix dumping inlined services (@nicolas-grekas)
  • bug #29054 [VarDumper] fix dump of closures created from callables (@nicolas-grekas)
  • bug #29102 [DI] fix GraphvizDumper ignoring inline definitions (@nicolas-grekas)
  • bug #29090 LoggingTranslator should implement SymfonyContractsTranslationTranslatorInterface (@desmax)
  • bug #29095 [TwigBridge] require the needed symfony/contracts package (@xabbuh)
  • bug #29107 [DI] dont track classes/interfaces used to compute autowiring error messages (@nicolas-grekas)
  • bug #29094 Add samesite attribute to session cookie after session migration (@rpkamp)
  • bug #29080 [FrameworkBundle] fix deps (@ro0NL)

Want to upgrade to this new release? Fortunately, because Symfony protects backwards-compatibility very closely, this should be quite easy. Read our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/15/2018 11:21 pm   Symfony Blog   Mirror   Link  

Contributed by
Nicolas Grekas
in #27009.

A cache stampede is a type of cascading failure that can occur when systems come under very high load. Consider a web application that caches some page to improve performance. When the cached version of that page expires and the server is under very heavy load, multiple users may be requiring the same uncached page, which could lead to the collapse of the system via exhausting shared resources.

There are multiple techniques to protect against "cache stampede". In Symfony 4.2 we added one called probabilistic early expiration, to the Cache component (we also added a lock-based one for when the cache is cold.)

This technique solves the stampede problem forcing the regeneration of the cached values before they expire. Whenever a value is read from the cache, the application makes a "probabilistic decision" to decide whether the value must be regenerated or not. Thanks to the formula used, the sooner the expiration of the cached value, the higher the probability of recomputing it.

In order to give better control of this "probabilistic decision", the get() method of CacheInterface has added a third optional argument called beta. It's a float value that defaults to 1.0, which provides optimal stampede protection.

Most of the times you don't have to care about this parameter. Symfony provides the right default value to protect your apps. However, you can set it to an arbitrary value or to 0 to disable this protection or to INF to force an immediate expiration of the cached value:

1
2
3
4
5
6
7
8
// this closure will be called when a cache key is missing from the backend
$callback = function () { ... return $computedValue; };

// when undefined, beta = 1.0
$productsCount = $cache->get('stats.products_count', $callback);

// beta = INF to force the immediate expiration of this cached value
$productsCount = $cache->get('stats.products_count', $callback, INF);

Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/15/2018 03:38 am   Symfony Blog   Mirror   Link  

This week, the upcoming Symfony 4.2 version added the loadEnv() method to replace the newly introduced loadForEnv() method. In addition a new Application::bootstrapEnv() method was introduced to define APP_ENV/APP_DEBUG from argv. Finally, the SymfonyCon Lisbon 2018 conference announced a scholarship program and a fundraising campaign.

Symfony development highlights

This week, 37 pull requests were merged (30 in code and 7 in docs) and 37 issues were closed (36 in code and 1 in docs). Excluding merges, 29 authors made 1,479 additions and 791 deletions. See details for code and docs.

2.8 changelog:

  • 46e3745: [HttpFoundation] replaced any preexisting Content-Type headers

3.4 changelog:

  • f898332: [DependencyInjection] don't track classes/interfaces used to compute autowiring error messages
  • 6cfd3de: fixed ini_get() for boolean values
  • 69ae468: [DependencyInjection] fixed GraphvizDumper ignoring inline definitions
  • 41eaba5: [VarDumper] fixed dump of closures created from callables
  • 6006448: [DependencyInjection] fixed dumping inlined services
  • d74a4eb: [Dotenv] don't use getenv() to read SYMFONY_DOTENV_VARS

4.1 changelog:

  • ca5b64d: [Serializer] allowed null values when denormalizing with constructor missing data

Master changelog:

  • 8cd0538: [HttpFoundation] added samesite attribute to session cookie after session migration
  • 626a610: [Routing] fixed dumping conditions that use the request
  • 664a032: [Dotenv] added loadEnv() as a smoother alternative to loadForEnv()
  • 9253199: [FrameworkBundle] define APP_ENV/APP_DEBUG from argv via Application::bootstrapEnv()
  • 1b82e56: [OptionsResolver] micro optimizations and simplifications

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2018-11-26 Clichy - 2018-11-26 Clichy - 2018-11-26 Clichy
11/11/2018 03:34 am   Symfony Blog   Mirror   Link  

For the second year in a row, we’re very pleased to launch our scholarship program! We are super excited to open the scholarship process for this year’s SymfonyCon Lisbon 2018, December 6th and 7th. We hope to help the Symfony community members who can’t afford to attend the conference to be part of this great event.

The scholarship program is part of the Diversity Initiative which was launched last year at SymfonyCon Cluj and is led by Lukas Kahwe Smith, a long time Symfony core team member. Lukas recently posted an update about the Diversity Initiative, if you didn’t read it you can find his blog post here.

Fundraising

This year, we’d like to call the entire Symfony community to contribute to our scholarship program by donating funds to help us cover the scholarships expenses for SymfonyCon Lisbon 2018. We aim to offer 3 scholarships at SymfonyCon Lisbon 2018 and we need your help. We’re thus opening a fundraising campaign to collect enough money to offer 3 scholarships to people who cannot join us at the conference for financial reasons. You can donate via our Symfony page on Open Collective website. Anyone can donate on Open Collective, a company or an individual. You can donate the amount you want and either become a backer or a Sponsor! After your donation, you’ll automatically get a PDF invoice.

Our objective is to receive enough money to cover the 3 scholarships we’d like to offer at SymfonyCon Lisbon. In order to be able to cover these 3 scholarships, we aim to collect a minimum of 4 000€ ($4,500) to cover the conference ticket, travel (flight or train tickets from the city of departure to Lisbon) and accomodation for 3 nights per grant recipient. If we exceed this minimum amount and have enough funds to provide more scholarships, we’d be very pleased to extend our scholarship offer to more people. All the available funds and the submitted expenses will be available on our page so everyone can see them. We’ve chosen Open Collective because of its mission to operate in full transparency and because we want to involve the community in this initiative as much as possible.

If you want to help us in our Diversity Initiative, you can donate here.

Scholarship process

Application process for scholarships at SymfonyCon Lisbon 2018 is now open until November 16th. You just need to fill in a form to submit your application. SymfonyCon’s scholarship program is aimed to support Symfony community members who want to attend the conference, but cannot without the scholarship. Anyone regardless of gender, gender identity and expression, sexual orientation, ability, physical appearance, race, ethnicity, age, religion, or socioeconomic status can apply for a scholarship.

We want to include, encourage and recognize people from all backgrounds no matter where you come from. If you cannot attend the conference without financial aid, you are eligible to our scholarship program. We will consider every application. Priority will be given to underrepresented groups such as women, minorities, LGBTQIA and people with disabilities, or other underrepresented groups who will be unable to attend the event without financial support. Students are welcome!

Within the Symfony community, we support diversity and inclusion and are proud to launch our second scholarship program.

Apply here for the SymfonyCon’s scholarship program until Friday November 16th 2018.

The selection process for the scholarship will be handled by the SymfonyCon Lisbon organizers, Lukas Kahwe Smith (Diversity Initiative leader) and the CARE team. We’ll announce the grant recipients on November 20th.

We’d like to thank in advance all the people who will support the scholarship program and help us build the Diversity Initiative. If you have any questions regarding the scholarship program or the SymfonyCon Lisbon, please contact us at event[at]symfony.com. If you want to have more information about our Code of Conduct, you can find it here.

See you soon at the conference!


Be trained by Symfony experts - 2018-11-12 Clichy - 2018-11-12 Clichy - 2018-11-14 Clichy
11/08/2018 08:08 am   Symfony Blog   Mirror   Link  

Fallback for internationalized routes

Contributed by
Thomas Calvet
in #27957.

In complex internationalized apps it's common to define different contents for each regional locale (e.g. en_GB for British English and en_US for American English). However, routes (or at least some of them) could be the same for all regions, so it's cumbersome to define duplicated routes:

1
2
3
4
5
6
7
8
9
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route({ "en_GB": "/about-us", "en_US": "/about-us" }, name="about")
 */
public function about()
{
    // ...
}

In Symfony 4.2 you can define internationalized routes without the region part and Symfony will match them ignoring the region part of the locale:

1
2
3
4
5
6
7
/**
 * @Route({ "en": "/about-us" }, name="about")
 */
public function about()
{
    // ...
}

In this example, both en_GB and en_US will match the en route.

ICU parent locales as fallback locales

Contributed by
Chris Wilkinson
in #28070.

Currently, when some content is not found for some locale (e.g. es_AR for Argentinian Spanish) Symfony uses the region-less locale (es in this case) as the fallback locale.

However, the ICU project defines "parent locales" for some languages (English, French, Spanish, Portuguese, etc.) In Symfony 4.2 we now use those parents as the first fallback locale. The previous example will now work as follows:

  • Use es_AR content if it exists;
  • Otherwise, fallback to the es_419 parent locale (which is the "international Spanish for Latin America and Caribbean region");
  • Otherwise, fallback to es.

Identity translator as fallback

Contributed by
Yonel Ceruto
in #28523.

When using certain features of Symfony Forms in an application that hasn't installed the Translation component you may find errors like "The helper "translator" is not defined".

In Symfony 4.2 we've added an "identity translator" helper which acts as fallback when the Translation component is not installed. This identity translator doesn't actually translate anything and it just returns the given content.

Update XLF translations by default

Contributed by
Alexis Boyer
in #27935.

XLIFF is officially recommended by Symfony as the format to use for your translations. That's why in Symfony 4.2 the translation:update command has changed the default value of its output-format option from yml to xlf.

It's a minor change, but it will save you from typing --output-format=xlf when running this command.

Lint multiple XLIFF dirs or files

Contributed by
Yonel Ceruto
in #28522.

The lint:xliff command has also improved in Symfony 4.2 to support linting multiple directories and files at once.

Moreover, the command is now much faster to execute because the validation is done using local XSD files. This will solve the timeout problems you may have found in the past.

1
2
$ ./bin/console lint:xliff translations/messages.en.xlf translations/messages.es.xlf
$ ./bin/console lint:xliff translations/ legacy_translations/ data/translations/messages.en.xlf

Be trained by Symfony experts - 2018-11-12 Clichy - 2018-11-12 Clichy - 2018-11-14 Clichy
11/08/2018 03:58 am   Symfony Blog   Mirror   Link  

The conference is now coming in one tiny month. We are so excited to meet you at SymfonyCon Lisbon 2018! We are working hard to offer you an incredible conference experience. You are not registered yet? Don’t miss the only international event about Symfony!

If you are still wondering why you should join us in Lisbon from December 6th to 8th, read our latest blog post about the 3 top reasons to come to SymfonyCon Lisbon 2018 and in case you are still hesitating, here are 3 more top reasons to come to the conference!

  • Conference social event! Let’s not forget the super social mixer we have planned for you on the evening of December 6th after the end of the first conference day. We'll be super happy to welcome all the attendees to the conference social event. We'll share drinks and snacks, in a relaxed atmosphere. The location will be announced soon so stay tuned for more details. It's one of the coolest moment of the conference when you can meet, exchange and chill out with everyone from the conference: attendees, speakers, sponsors... We know you’ll just love it!

  • Meet the Symfony Core Team! We'll have the pleasure to welcome several Symfony Core Team members during the conference and we'll even have a Symfony Community booth where you'll be able to meet them. You always wondered who is in the Core Team and never had the chance to meet them in real life? You have a ton of questions to ask them? Come to Lisbon and you'll be able to listen to their talks and connect with them!

  • The Hackday! On the last day of the conference, on Saturday December 8th, we're organizing a Hackday. This is a dedicated moment during the conference to encourage all Symfony contributions. There are several ways to contribute to Symfony: help to write, review or translate the documentation; work on current issues and PRs to close as many of them as possible to improve Symfony’s development; mentor new contributors; learn how to be involved in the local Symfony community around you; meet other people from the community to exchange best practices, tips… There are a lot to do during the Hackday! If you never attended one before and don’t know how to contribute to Symfony, this is definitely the place to be. Usually we organize several work groups where people can gather to work on specific topics. It’s also a good way to put into practice and test what you just learned during the conference days. Plus, there will be food and coffee all day. The Hackday will start around 9:30 am and end around 4:30pm, you don’t even have to stay the entire day to contribute. But in case you stay all day, you’ll still have some time left after the Hackday to enjoy Lisbon!

And now, are you still hesitating? Oh, did I mention that on top of that you'll get your free conference t-shirt? If you collect them, don't miss this year's conference t-shirt to bring back this new one to your collection! Ready to join us?

Basic conference breakdown:

  • Pre-conference workshops: December 4th and 5th (a very few seats left for most of the workshops, you’d better secure your workshop seat asap if you want to buy a combo ticket)

  • Conference days (schedule of talks): December 6th and 7th, 3 tracks are waiting for you! Discover the schedule!

  • Hackday: December 8th (or the Contribution Day to Symfony as mentioned above)

Buy your ticket at regular price now, only available until November 12th (included), after that date the price will increase! Enjoy the regular rate while it’s still possible!

We’re counting on you to make this SymfonyCon legendary! Symfony is a vibrant community only because you make it so. Bring your team with you and share the excitement! See you soon!

PS: there are some remaining seats for the Sylius, Messenger, API Platform, Modern JS/Webpack and Symfony 4 workshops.


Be trained by Symfony experts - 2018-11-12 Clichy - 2018-11-12 Clichy - 2018-11-14 Clichy
11/07/2018 08:38 am   Symfony Blog   Mirror   Link  

Contributed by
Laurent Voullemier
in #27914.

Security voters are the key feature of Symfony's authorization mechanism. They provide the most granular way of checking permissions (e.g. "can this specific user edit the given item?").

In order to grant or deny permission, all the voters' decisions are aggregated by the Access Decision Manager. Then, depending on your application config, permission is granted if all voters said yes (unanimous), or if the majority said yes (consensus), or if at least one voter said yes (affirmative).

Sometimes, when your security logic is complex, you may need to know exactly why some permission was granted. Symfony Profiler already shows some details about voters:

However, the information is not as detailed as it should be. In Symfony 4.2, we improved this panel to display all the information available about the voters decisions and not only the aggregated results:


Be trained by Symfony experts - 2018-11-12 Clichy - 2018-11-12 Clichy - 2018-11-14 Clichy
11/07/2018 03:13 am   Symfony Blog   Mirror   Link