eZecosystem / Mirror / Symfony Blog

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  

After months of community work, I'm am thrilled to be able to talk about the release of Webpack Encore 0.21.0. This represents a huge step forward to stay with the latest versions of industry-standard tools and a bunch of great features along the way.

So, what changes and improvements happened? Let's find out!

WebpackEncoreBundle & encore_entry_script_tags()

Besides the Webpack 4 upgrade itself (described below) the most noticeable change is that a new bundle has been created: WebpackEncoreBundle. If you've previously installed the symfony/webpack-encore-pack, you can remove it and install the bundle instead:

1
2
composer require symfony/webpack-encore-bundle
composer remove symfony/webpack-encore-pack

Notice there is no --dev flag for symfony/webpack-encore-bundle. That's on purpose: it contains a new feature that makes it much easier to include the script and link tags for an entry:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{# templates/.../checkout.html.twig #}

{% block javascripts %}
    {{ parent() }}

-     <script src="{{ asset('build/checkout.js') }}"></script>

+     {{ encore_entry_script_tags('checkout') }}
{% endblock %}

{% block stylesheets %}
    {{ parent() }}

-     <link rel="stylesheet" href="{{ asset('build/checkout.css') }}">

+     {{ encore_entry_link_tags('checkout') }}
{% endblock %}

Why have we added these functions? Because using these functions gives you versioning and CDN support for free, as well as enabling the new "Split Chunks" feature described below.

Webpack 4, Babel 7 and Major Upgrades

The main focus of this release was to upgrade Encore to use the latest versions of Webpack & Babel. Webpack 4 contains a long list of improvements - like faster build times and a new way to "split" your built files into more optimized pieces (more on that later). Babel 7 is also a huge release - it contains optimizations and support (via @babel/preset-env) for browserslist (more on that later).

Several other libraries were also upgraded - see the CHANGELOG for full details. If you're using Encore's features exclusively, you shouldn't have any problem with these major version upgrades. If you've added custom features - be sure to check the changes for each library.

splitChunks() & encore_entry_script_tags()

One of the biggest innovations in Webpack 4 is SplitChunksPlugin. This solves the problem of duplicated code between multiple compiled entry files. Before Webpack 4, this was solved in Encore via the createSharedEntry() method. This method will not go away soon, but Webpack now has a better option.

Encore 0.21.0 adds a new splitEntryChunks() method. When this feature is enabled, Webpack's SplitChunksPlugin will use an optimization algorithm to automatically "split" the final JavaScript and CSS files into multiple pieces. For example, an entry called "app" will normally output app.js and app.css files. But with splitEntryChunks(), it may output app.js and vendor~app.js (which would contain code shared by other entry files) as well as app.css and vendor~app.css.

But this now means you may need multiple script and link tags in your template! To solve this problem, Encore outputs a new entrypoints.json file that contains all the JavaScript and CSS files needed for each "entry". The new WebpackEncoreBundle Twig functions know how to read from this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{# templates/.../checkout.html.twig #}

{% block javascripts %}
    {{ parent() }}

    {#
        May now render multiple script tags:
            <script src="/build/runtime.js"></script>
            <script src="/build/checkout.js"></script>
            <script src="/build/vendor~checkout.js"></script>
    #}
    {{ encore_entry_script_tags('checkout') }}
{% endblock %}

{% block stylesheets %}
    {{ parent() }}

    {#
        May now render multiple link tags:
            <script src="/build/checkout.css"></script>
            <script src="/build/vendor~checkout.css"></script>
    #}
    {{ encore_entry_link_tags('checkout') }}
{% endblock %}

That's it! Webpack will intelligently "split" your entry files and the correct script and link tags will always be rendered. The manifest.json file is still output by Encore, but is only used if you need to refer to a static asset (like an image) from your Twig template via the asset() function.

New runtime.js File

This version of Encore also introduces an optional new output file called runtime.js. You should explicitly enable or disable it by calling either enableSingleRuntimeChunk() or disableSingleRuntimeChunk(). If you enable it, a new runtime.js file will be output and needs to be included in your page (but encore_entry_script_tags() will handle this automatically)

What's the point of runtime.js? Suppose you include multiple entry JavaScript files on the same page - like an app.js in your layout and also checkout.js when you're on a checkout page. Then:

  • With enableSingleRuntimeChunk(): if the same module (e.g. jquery) is required by both entry files, they will require the same object.
  • With disableSingleRuntimeChunk(): if the same module (e.g. jquery) is required by both entry files, each will receive a different object.

Using enableSingleRuntimeChunk() will give you the same behavior as Webpack 3, but you can choose whichever setting works better for your app.

New copyFiles() Feature

One of the most-asked-for features in Encore is the ability to copy static files into your build directory. Until now, we recommended using the copy-webpack-plugin. This plugin is great, but if you used version hashes in your filenames, the manifest.json file would not contain the correct key for this copied file (the key would be the versioned/hashed filename). In practice, this made it impossible to version your copied files with filename hashes.

To fix this, Encore now has a copyFiles() method! It's simple: use it to copy files from one directory (e.g. assets/images) into your "build" directory. If versioning is enabled, all files are given version hash names and are included in manifest.json so you can fetch the correct filename via the asset() function in Twig.

Async Code Splitting out-of-the Box

Did you know that Webpack allows you to require modules asynchronously, only when you need them? The feature is called Code Splitting. It's not new, but in the latest version of Encore, you can use it without any extra configuration:

1
2
3
4
5
6
7
$('.js-open-video').on('click', function() {
    // async load the VideoPlayer module
    import('./components/VideoPlayer').then(({ default: VideoPlayer }) => {
        // once it loads, use it!
        const player = new VideoPlayer('some-element');
    });
});

browserslist Support

There are several tools in Encore that need to know what versions of browsers your site needs to support. For example, both Babel and autoprefixer (from PostCSS) will compile your code differently if you need to support older browsers versus only newer browsers.

Until now, there was no one place to configure this. But, thanks to upgrades to @babel/preset-env, you can now set your browsers via a browserslist key in package.json.

For more details, see the browserslist documentation for Encore.

Support for Uglifying ES6 Code

Before this release, Uglify (the library that minifies your JavaScript for production), was unable to process ES6 code. This meant that you were forced to transpile all your JavaScript to ES5 code, even if your site didn't need to support older browsers.

Because of this, Uglify was replaced with terser - a fork of Uglify that processes ES6 code. You shouldn't notice any difference in your app unless you use the configureUglifyJsPlugin() method (use configureTerserPlugin() now).

Ready to Upgrade?

Because this is a big release, upgrading requires a few steps:

  1. Install the bundle via composer require symfony/webpack-encore-bundle
  2. Remove the webpack-encore-pack via composer remove symfony/webpack-encore-pack
  3. Update your version constraint in package.json for @symfony/webpack-encore to ^0.21.0
  4. Run yarn upgrade
  5. Replace your manual script and link tags with the new encore_entry_script_tags() and encore_entry_link_tags() functions.

And, over time, replace createdSharedEntry() with splitEntryChunks(). If you have any issues, please report them on the symfony/webpack-encore repository.

Enjoy!


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

Contributed by
Kévin Dunglas
in #28875.

The WebLink component introduced in Symfony 3.3 provides tools to manage the Link HTTP header needed for Web Linking when using HTTP/2 Server Push as well as Resource Hints. In practice, it can improve the performance of your web apps dramatically.

In order to simplify its usage, in Symfony 4.2 we've added a new addLink() shortcut to AbstractController. For example, this is how you can preload a CSS file (to send it before the browser requests it):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/Controller/BlogController.php
namespace App\Controller;

use Fig\Link\GenericLinkProvider;
use Fig\Link\Link;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlogController extends AbstractController
{
    public function index(Request $request)
    {
        // BEFORE
        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
        $request->attributes->set('_links', $linkProvider->withLink(new Link('preload', '/app.css')));

        // AFTER
        $this->addLink($request, new Link('preload', '/app.css'));

        return $this->render('...');
    }
}

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

This week, Symfony 2.8.47, 3.4.18 and 4.1.7 maintenance versions were released. In addition, the first beta of Symfony 4.2 was released, including recently added new features like some debug:autowiring command improvements.

Symfony development highlights

This week, 51 pull requests were merged (35 in code and 16 in docs) and 31 issues were closed (22 in code and 9 in docs). Excluding merges, 26 authors made 17,135 additions and 5,508 deletions. See details for code and docs.

2.8 changelog:

  • 36e2983: [Console] removed duplicate condition
  • 5a2969c: fixed ini_get() for boolean values

3.4 changelog:

  • 5d11205: [DependencyInjection] fixed tags on multiple decorated service

Master changelog:

  • 3263175: [FrameworkBundle] made debug:autowiring list useful services and their description
  • 2cd1e11: [Messenger] made TraceableMiddleware decorate a StackInterface instead of each middleware to free the callstack from noisy frames
  • 225746b: [Messenger] mark the component as experimental for 4.2
  • d2b8014: [Messenger] made senders and handlers subscribing to parent interfaces receive all matching messages (wildcard included)
  • d699036: [DependencyInjection] use filter_var() instead of XmlUtils::phpize() in EnvVarProcessor
  • 79bbee2: [VarDumper] added a caster for Memcached

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


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

Introducing the new online Symfony Certification

We are extremely pleased to announce that the Symfony and Twig certification exams are available online! It means that you can now take the exam from home or from your office! You need your computer, a web cam and a stable Internet connection!

Fabien Potencier introduced the Symfony certification program during his keynote at SymfonyLive Paris 2012 and the first certification session was organized during the conference. At that time, the certification was only organized during official Symfony events. The exam was hold in the conference venue and proctored by the SymfonyLive team. Then different exam sessions were organized during the year at SensioLabs’ offices. The first certification was dedicated to the 2.3 version of the framework.

In October 2013, the Symfony certification was launched worldwide and available in 4,000 physical exam centers to enable much more people to take it. At the same time we introduced the « Advanced level » as an intermediary step before the « Expert level ». Since then, the certification exam was only available in one of the 4,000 worldwide exam centers available.

The Symfony 3 certification was launched in December 2015 and the Twig certification was introduced in June 2016. Lately this year, on March 30th, we introduced the Symfony 4 certification.

We are now moving forward with the certification! We wanted to enable everyone to take any exam no matter where you are in the world 1: as long as you have a computer, a web cam and a stable Internet connection, you can take it. As of today, the certification exam is only available online for any Symfony versions and Twig. You don’t have to go to any exam center, schedule an appointment and physically go there to take the exam. Now it’s faster and easier to take the exam, you can take it from your own home or office.

How do the certification exams work? Any Symfony certification lasts 90 minutes and includes 75 questions divided into 15 topics. Check here the exam topics of all the Symfony certification exams. The Twig certification lasts 60 minutes and includes 45 questions divided into 8 topics. Find here all the exam topics of the Twig certification exam.

Both certifications, the Symfony one and the Twig one, do not include any written answers or lines of code to write. You have 3 types of questions : True / False, Single answer or Multiple choice. Your online certification exam will be proctored during the entire test, the proctor will ask you to test your camera and show the room where you take the exam before starting the test. Don't forget to test and check your camera and network connection before starting!

To book your online certification exam, follow these steps:

1- Buy your certification voucher for Symfony 3 or 4 version or for Twig

2- Create your candidate account or log in to your existing account

3- Activate your voucher to schedule an exam appointment

4- Take the exam online in your own home or office and get your result immediately!

When you buy your certification voucher and activate your voucher, you have to wait for 24 hours before scheduling your exam. You can buy your certification voucher today and become a Symfony or a Twig certified developer tomorrow!

We are proud to count about 400 certified Symfony and Twig developers in our community and we’d like to congratulate again all the certified Symfony and Twig developers! You want to become a Symfony or a Twig certified developer? Book your certification voucher at the unique price of 250 € for Symfony and 149€ for Twig.

If you have any questions regarding the Symfony and Twig certification exams, please read our FAQ section where you’ll find more detailed information. Good luck!

1Exceptions of Cuba, Iran, North Korea, Sudan and Syria due to US Foreign policies.


Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/31/2018 04:56 am   Symfony Blog   Mirror   Link  

Contributed by
Kévin Dunglas
in #28533.

Since the introduction of the DotEnv component in Symfony 3.3, we've been working hard to improve the experience of using env vars to configure Symfony apps. In Symfony 4.2, we've added a new loadForEnv() method to allow you define different env vars per environment.

Instead of creating a single .env file at your project's root dir, you can now create one or more env var files. The values for the env var are looked for in the following order:

  • .env + environment name + .local (.env.dev.local, .env.test.local, .env.prod.local). These are the environment-specific settings overridden locally on your machine.
  • .env.local. Used for overriding values on your local machine. This file is loaded for all environments except test.
  • .env + environment name (.env.dev, .env.test, .env.prod). These are the files that define environment-specific settings. Useful for example to override settings like the database connection for tests.
  • .env. Same file as used by current Symfony apps.

We're working on a Symfony Flex recipe to bring this new feature into the full Symfony framework (see symfony/recipes #466). Once merged, you'll need to make the following changes in your app:

  • Rename .env.dist as .env (and commit it to the shared repository).
  • Rename .env as .env.local (and remove it from the shared repository).

Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/30/2018 06:46 am   Symfony Blog   Mirror   Link  

Contributed by
Nicolas Grekas
in #28970.

The debug:autowiring command displays all classes and interfaces that Symfony developers can use as type-hints for service autowiring. In previous Symfony versions, it looked like this when looking for something specific (e.g. the cache):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
$ ./bin/console debug:autowiring cache

Autowirable Services
====================

 The following classes & interfaces can be used as type-hints when autowiring:
 (only showing classes/interfaces matching cache)

 --------------------------------------------------
  Psr\Cache\CacheItemPoolInterface
      alias to cache.app
  Psr\SimpleCache\CacheInterface
      alias to cache.app.simple
  Symfony\Component\Cache\Adapter\AdapterInterface
      alias to cache.app
  Symfony\Contracts\Cache\CacheInterface
      alias to cache.app
  Symfony\Contracts\Cache\TagAwareCacheInterface
      alias to cache.app.taggable
 --------------------------------------------------

In Symfony 4.2 we improved this command to make the information easier to understand. The same search for cache now looks like this:

As you can see, the description of what the service does now appears above it. This description is taken from the PHPdoc of the related interface. Also, the autowire by type and name feature introduced in Symfony 4.2 is displayed (e.g. CacheInterface $cacheApp).


Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/29/2018 07:19 am   Symfony Blog   Mirror   Link  

This week, development activity focused on polishing the upcoming Symfony 4.2 version, which will be released in 5 weeks. We improved performance of service discovery for large applications and we optimized the way env vars are exported. We also improved the log filter in the Symfony profiler to support filtering by multiple criteria.

Symfony development highlights

This week, 71 pull requests were merged (40 in code and 31 in docs) and 31 issues were closed (18 in code and 13 in docs). Excluding merges, 35 authors made 3,601 additions and 2,063 deletions. See details for code and docs.

2.8 changelog:

  • 5c3d826: [FrameworkBundle] fixed broken exception message

3.4 changelog:

  • c2478d4: [Intl] updated the ICU data to 63.1

4.1 changelog:

  • 3dda3cc: [HttpKernel] clean away the NO_AUTO_CACHE_CONTROL_HEADER if there is no session
  • 76b2541: [Messenger] send using the routing_key for AMQP transport

Master changelog:

  • 426cf81: [Serializer] refactor and uniformize the config by introducing a default context
  • 60394bc: [Config] fixed slow service discovery for large excluded directories
  • 717ff2d: [DependencyInjection] optimized exporting variables
  • 07c46a2: [WebProfilerBundle] removed application name
  • 01dfca1: [WebProfilerBundle] added a channel log filter
  • 9d3621e: [OptionsResolver] trigger deprecation only if the option is used
  • a33725f: [FrameworkBundle] deprecated support for legacy directories in Translation commands

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/28/2018 03:48 am   Symfony Blog   Mirror   Link  

Contributed by
Andrei Igna
in #26486.

The Accept HTTP header is added by browsers to their requests to advertise which content types they are able to understand. These content types are expressed as MIME types.

The HttpFoundation component provides several utilities in its Request class to work with request formats and MIME types (such as getMimeType(), getFormat(), getRequestFormat(), getContentType(), getAcceptableContentTypes(), etc.)

In Symfony 4.2 we added a new method called getAcceptableFormats() which returns a simplified list of formats accepted by the client based on the Accept header. This simple list is what most apps commonly need to decide which format to serve:

1
2
3
4
5
6
7
8
9
// $request is an instance of Symfony\Component\HttpFoundation\Request

// BEFORE: this was the best method to get the list of accepted content types
$request->getAcceptableContentTypes();
// returns ['text/html', 'application/xhtml+xml', 'application/xml', '*/*']

// AFTER: the list returned by the new method is easier to understand and work with
$request->getAcceptableFormats();
// returns ['html', 'xml']

Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/26/2018 06:20 am   Symfony Blog   Mirror   Link  

Contributed by
Fabien Bourigault
in #28505.

The Serializer component is able to transform property names when serializing objects. For example, it can transform camel-cased properties like $firstName into snake-cased values like first_name.

For more complex cases, you can create name converters to map PHP property names to serialized names arbitrarily. In Symfony 4.2 we added another simpler way to do that. You can now configure name conversion rules using metadata and it works with PHP annotations (@SerializedName), XML config (serialized-name attribute) and YAML config (serialized_name key).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
namespace App\Entity;

use Symfony\Component\Serializer\Annotation\SerializedName;

class Person
{
    /** @SerializedName("customer_name") */
    private $firstName;

    public function __construct(string $firstName)
    {
        $this->firstName = $firstName;
    }

    // ...
}

When this object is serialized, the $firstName property will be called customer_name instead of first_name:

1
2
$serialized = $serializer->serialize(new Person('Jane'));
// {"customer_name": "Jane"}

Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/25/2018 06:05 am   Symfony Blog   Mirror   Link  

As part of the diversity initiative we in the beginning focused on putting systems into place to ensure that everyone can feel safe within our community. A major step was the adoption of the CoC and establishing of the CARE team, and maybe even more so by discussions within our community. We have made huge strides forward in this area with channels like #thankyou and #victory on the Symfony devs Slack. With these channels, where we celebrate all contributions and achievements no matter how small or large, we strife to create a more positive atmosphere. This has spilled over to other channels leading to open discussions about how to improve diversity and inclusion. We of course acknowledge that diversity and inclusion is a topic which requires a continuous learning process.

However, the obvious next step is to actively invite new developers to join our community and empower existing members to take the next step in making their voices heard. For this reason we published two new sections in our documentation: one for general mentoring and one for speaker mentoring.

The general #mentoring Slack channel is intended as a place where both newcomers and people seeking to take the next steps in their learning can find assistance. They can either ask questions as they come up or seek a more one-on-one approach with a mentor. A mentor can help you through anxieties during your first steps, as it is possible to discuss things outside of the public eye, building a trust relationship with an experienced community member. Aside from this, there is also the #contribs Slack channel for people that specifically seek help in contributing to the Symfony core.

As this entire concept is still quite informal, we do ask for feedback on how we can improve: Does it need more formal processes? Do we need regular “mentor meets mentee” events?

Another aspect we want to focus on is getting more people comfortable with sharing their knowledge in the community. For this purpose we have created a #speaker-mentoring Slack channel. Similar to the #mentoring Slack channel, the goal is to provide a place where beginners can ask questions and perhaps find a mentor. A mentor can help finding topics to submit to for call-for-papers and review proposals and slide decks. They can even do trial runs of your presentation with you. Remember: your first talk doesn’t have to be at a SymfonyCon, it can also be at a local user group or at your place of employment.

Once again, we are very much looking for feedback: Should we do regular virtual conferences for first time speakers? Are finances and logistics holding you back more than lack of help with getting your talk prepared?

As a final note, I wanted to mention Joni’s work as part of the Dutch PHP Conference. She contacted me recently about what we have done to document some advice for conference organizers in terms of diversity and inclusion in the Symfony community. Unfortunately, all I had to offer was a ticket with a lot of links. A week or two passed, and Joni came back with this amazing document that is now on Github. It contains a very comprehensive list of topics organizers should consider, with useful advice on how to implement these and links for further reading.

I would like to invite everyone who organizes events in the Symfony community to have a look. Even if you just implement a few of these items, it is already a step forward! Of course the reason this document was put on Github was to make it easy for people to collaborate on it and continuously improve and expand it. Semi-related, it would be cool if maybe some people from the Symfony community could help to add support for a blind review process to the opencfp platform.


Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/24/2018 02:26 pm   Symfony Blog   Mirror   Link  

Symfony's Backward Compatibility Promise ensures smooth upgrades in your projects because it forbids backward compatibility breaks in minor releases. Instead of changing or removing existing features, we mark them as deprecated and change them in the next major Symfony version.

The UPGRADE-4.2.md document explains all deprecations in details and you'll see them too in the Web Debug Toolbar, the profiler and when running tests. This article summarizes the most important deprecations so you can start upgrading your Symfony 4 apps.

Deprecated a template directory

Contributed by
Yonel Ceruto
in #28891.

Storing the app templates in src/Resources/views/ is now deprecated. You must store them in the directory defined in the twig.default_path config option in config/packages/twig.yaml, which is templates/ by default.

Deprecated the Kernel name and the root dir

Contributed by
Fabien Potencier
in #28809 and #28810.

The KernelInterface::getName() method and the kernel.name parameter have been deprecated. There's no alternative to them because this is a concept that no longer makes sense in Symfony applications.

If you need a distinctive ID for the kernel of the application, you can use the KernelInterface::getContainerClass() method and the kernel.container_class parameter.

Similarly, the getRootDir() method and the kernel.root_dir parameter have been deprecated too. The alternative is to use the getProjectdir() and kernel.project_dir method introduced in Symfony 3.3:

1
2
3
4
5
6
7
8
9
# 'root_dir' is where the Kernel class is stored (src/ by default) and
# 'project_dir' is the main project directory
services:
    _defaults:
        bind:
            # Before
            $dataDir: '%kernel.root_dir%/../var/data/'
            # After
            $dataDir: '%kernel.project_dir%/var/data/'

Deprecated some console options

Contributed by
Robin Chalas
in #28653.

In Symfony 4 applications, console commands are executed in the environment defined by the APP_ENV env var. On local machines (and on some production servers) this env var is commonly defined in the .env file.

If you want to run commands in another environment, change the value in that .env file. If you want to change the environment just for some command or to do a quick test, you can set the APP_ENV and APP_DEBUG env vars before running the command.

In previous Symfony versions you could override the environment and the debug config with the --env and --no-debug command options, but they have been deprecated in Symfony 4.2:

1
2
3
4
5
# Before
$ php bin/console command_name --env=test --no-debug

# After
$ APP_ENV=test APP_DEBUG=0 php bin/console command_name

In addition to changing the commands executed locally, you may need to check your deployment commands and the cron tasks defined in your production servers.

Deprecated ContainerAwareCommand

Contributed by
Robin Chalas
in #28415.

The ContainerAwareCommand class has been deprecated. It was used in the past to create commands extending from it so they had direct access to the app service container. The alternative is to extend commands from the Command class and use proper service injection in the command constructor, as explained in the main article about the Symfony Console.

TIP: use the make:command utility provided by the MakerBundle to generate commands quickly and following the Symfony recommendations.

Deprecated the base Controller class

Contributed by
Samuel Roze
in #28243.

The base Controller class is the optional class your controllers can extend from to get access to some useful shortcut methods (such us $this->render()). This Controller class has been deprecated in favor of AbstractController.

The new AbstractController base class has the same shortcuts but it's more restrictive about services. You cannot use the $this->get() shortcut to get services. You must follow the modern practices of injecting services in your controller constructor or in the controller action.

TIP: use the make:controller utility provided by the MakerBundle to generate controllers quickly and following the Symfony recommendations.

Deprecated process commands as strings

Contributed by
Nicolas Grekas
in #27821.

Passing commands as strings to the Process class has been deprecated. The alternative is to pass an array of the command parts (name, arguments, options):

1
2
3
4
5
6
7
use Symfony\Component\Process\Process;

// Before
$process = new Process('ls -l');

// After
$process = new Process(['ls', '-l']);

Deprecated tree builders without root nodes

Contributed by
Christian Flothmann
in #27476.

This deprecation won't affect directly to most developers because it's related to the configuration classes of dependency injection. However, you'll see lots of these deprecation messages because of the bundles used in your application.

Fixing this deprecation will be simple in most cases, so you may contribute a fix to your favorite third-party bundle:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

// Before
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_root');
$rootNode->...()->...()->...();

// After
$treeBuilder = new TreeBuilder('acme_root');
$treeBuilder->getRootNode()->...()->...()->...();

Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/24/2018 03:01 am   Symfony Blog   Mirror   Link  

SymfonyCon Lisbon opens its doors from December 6th to December 8th. Join us for our annual international conference in Lisbon, Portugal, to attend the international Symfony reunion and meet with members of the Symfony community from all over the world!

Secure now your ticket to the conference (including our famous Hackday) and our workshops at regular price when they are still available, some pre-conference workshops are already sold out and others only have a few seats left! Check the workshops schedule to create your personnalized combo.

You are still hesitating in joining this unmissable event? Well, here are 3 top reasons to grab your ticket and jet over to Lisbon:

  • Meet Symfony experts from all over the world! Symfony hit the Billion download milestone last year and is now approaching to the 2 Billion downloads. Our community is growing at an exponential rate and we are expecting more than 1,000 Symfony enthusiasts from around the globe. What better way to make new contacts, learn new development techniques and even better practices, exchange with partners and sponsors… this is THE place to be for open source innovation.

  • Multi-track schedule! Enjoy listening to our specially-selected speakers, all of whom will share real-life, real-project experiences, difficulties and solutions, tips and best practices for how to use the Symfony framework and PHP in the best way for your project! We have 3 tracks per day which means 3 talks per hour, you can listen to a talk from the track of your choice between: beginner, advanced, PHP on conference day 1 or the Unconference on conference day 2! Listen to top-list speakers, among them Fabien Potencier, Symfony founder/project lead; Anthony Ferrara, Diana Ungaro Arnos, Jordi Boggiano, Nicole Cordes, Ryan Weaver and many others… who will deliver their awesome talks! Check the schedule now to plan your best conference experience.

  • Unconference track! This year again, we’ll have at SymfonyCon Lisbon an Unconference track on the second day of the conference. How does it work? It's easy! If you want to speak at the Unconference, you just have to sign up for your talk on our paperboard on the first day of the conference or directly on the day of the Unconference. You can talk for 20, 30 or 40 min depending on the topic you'd like to share and you don't even need to prepare slides! The best is to sign up the day before the Unconference track on December 6th, to enable everyone to know what you'll be talking about in advance. You can talk about any topic related to Symfony, its ecosystem or its community. Never tried the Unconference experience before? That's the perfect occasion to join SymfonyCon Lisbon!

Are you in? Will you join us there? Did I already mention that the conference will be organized in Lisbon, home of the delicious Pastel de Nata, great Fado, beautiful Azulejos (Tiles), wonderful kilometers of white sand beaches and much more?

Join us in Portugal to celebrate the framework, open source innovations and the multi-faceted world of PHP! Show up, listen carefully and stay tuned to discover the latest news about Symfony and PHP! Buy your ticket now!

We’re looking forward to meeting you there!


Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris
10/23/2018 07:25 am   Symfony Blog   Mirror   Link  

This week, Symfony 4.2 deprecated the kernel name and the usage of getRootDir() and kernel.root_dir. Meanwhile, the Form component added a new help_attr option and the Messenger component renamed and reorganized some of its classes.

Symfony development highlights

This week, 56 pull requests were merged (37 in code and 19 in docs) and 46 issues were closed (26 in code and 20 in docs). Excluding merges, 40 authors made 3,116 additions and 4,274 deletions. See details for code and docs.

2.8 changelog:

  • 8322494: [Security] convert InsufficientAuthenticationException to HttpException with 401 status code

3.4 changelog:

  • dc11f7b: [FrameworkBundle] uniformize errors when a component is missing
  • fdc9e09: [FrameworkBundle] update translation commands for the new directory structure

4.1 changelog:

  • 72ab16d: [DependencyInjection] fixed default undefined env to empty string during compile
  • 0daf414: [Config] fixed @method annotation

Master changelog:

  • 2b34f2b: [Validator] use constraint options instead of properties
  • 76f80e9: [HttpFoundation] made ResponseHeaderBag::makeDisposition static
  • 5fda7e2: [HttpKernel] deprecated the Kernel name
  • e85f6d4: [HttpKernel] deprecated usage of getRootDir() and kernel.root_dir
  • 7048679: [FrameworkBundle] avoid calling getProjectDir() on KernelInterface
  • f0814e1: [Form, TwigBridge] added help_attr
  • bcff647: [Serializer] improved perf a bit by not using a signaling exception when not needed
  • 91a2d75: [WebProfilerBundle] redesigned the log message filter
  • 4d757b5: [Messenger] renamed "envelope items" and move them in the "Stamp" namespace
  • 915870e: [Serializer] fixed MetadataAwareNameConverter break denormalization
  • c620a3b: [TwigBundle] deprecated support for legacy templates directories
  • 316e95c: [WebProfilerBundle] replay referer URL

Newest issues and pull requests

They talked about us

Upcoming Symfony Events

Call to Action


Be trained by Symfony experts - 2018-10-24 Clichy - 2018-11-5 Paris - 2018-11-5 Paris
10/21/2018 04:32 am   Symfony Blog   Mirror   Link  

Contributed by
Maxime Veber
in #27742.

The Symfony Process component executes commands taking care of the differences between operating system and escaping arguments to prevent security issues. One of the features it provides is the wait() method, which blocks the app execution until the given process has finished.

However, for some kinds of commands (such as long running processes) you can't use this method because the process never ends. That's why it's common to find code like this, which waits a few seconds for the process to start:

1
2
3
4
5
6
7
use Symfony\Component\Process\Process;

$process = new Process(['/usr/bin/php', 'slow-starting-server.php']);
$process->start();

// wait a few seconds for the process to be ready
sleep(3);

However, this code is fragile because the process may take longer to be ready than the given time. In Symfony 4.2 we've added a new waitUntil() method which receives a callback as argument and keeps waiting until the callback returns true.

The callback is called repeatedly whilst the process is still running, passing in the process output and its type (Process::ERR or Process::OUT) as its arguments.

In the above example, instead of waiting a fixed number of seconds, you could wait until some text is printed in the console showing that the process is ready:

1
2
3
$process->waitUntil(function ($type, $output) {
    return $output === 'Ready. Waiting for commands...';
});

Be trained by Symfony experts - 2018-10-24 Clichy - 2018-11-5 Paris - 2018-11-5 Paris
10/19/2018 05:45 am   Symfony Blog   Mirror   Link  

Symfony meetup in Vietnam

We’re super excited to announce that for the first time ever a Symfony meetup will be organized in Vietnam next month. For this great occasion, Fabien Potencier will be speaking there about “What’s new in Symfony 4”. For one night only, join him on November 8th for an exclusive event to get to know the latest version of Symfony in Hồ Chí Minh. We'd like to give a warm thank you to Pierre Joye who helped putting this meetup together, thank you for your help and Symfony support from there!

The free meetup is organized by NFQ Asia at Dreamplex 195 Dien Bien Phu St., Quận Bình Thạnh, Thành Phố Hồ Chí Minh from 6:30 pm to 9 pm. The talk will be followed by a networking time to share pizzas, beers and soft drinks in a relaxed way. A great opportunity for all Symfony and PHP lovers to gather, learn some new knowledge, and network with like-minded techies.

Don’t forget to register here to the meetup if you plan to go there! We are very pleased to meet the Vietnamese Symfony community there!


Be trained by Symfony experts - 2018-10-24 Clichy - 2018-11-5 Paris - 2018-11-5 Paris
10/18/2018 02:47 am   Symfony Blog   Mirror   Link  

Symfony's security system has always been flexible. But over the past few years, it's also become increasingly easy to tap into that power: by creating Guard authenticators and voters for complex authorization rules.

But, we can do more. For example, Symfony security users are so flexible, they can be confusing to set up. And creating a Guard authenticator, while clear and powerful, requires some work. Can we have both flexibility and rapid development? I think so - thanks to two new commands added to MakerBundle.

make:user

Contributed by
Ryan Weaver
in #250.

Ready to start your security system? First you need a user. But, does your entity need to be saved to the database? And is your app responsible for checking passwords? MakerBundle 1.7 will guide you through these decisions and generate exactly what you need:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$ php bin/console make:user

The name of the security user class (e.g. User) [User]:
> User

Do you want to store user data in the database (via Doctrine)? (yes/no) [yes]:
> yes

Enter a property name that will be the unique "display" name for the user
(e.g. email, username, uuid) [email]:
> email

Will this app need to hash/check user passwords? Choose No if passwords
are not needed or will be checked/hashed by some other system (e.g. a single sign-on server).
Does this app need to hash/check user passwords? (yes/no) [yes]:
> yes

created: src/Entity/User.php
created: src/Repository/UserRepository.php
updated: src/Entity/User.php
updated: config/packages/security.yaml

That's it! Depending on your answers, the command will create a User class/entity and update your security.yaml file to configure a secure password encoder (if needed) and a user provider. The generated code has clear comments so you can continue updating everything for your needs.

make:auth

Contributed by
Nicolas Philippe
in #266.

Now that you have a User class, it's time to let your users log in. Want a complete form login system in one command? In MakerBundle 1.8, it's no problem. The new make:auth command can create an entire form authentication system, or an empty authenticator, based on your answers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ php bin/console make:auth

What style of authentication do you want? [Empty authenticator]:
[0] Empty authenticator
[1] Login form authenticator
> 1

The class name of the authenticator to create (e.g. AppCustomAuthenticator):
> LoginFormAuthenticator

Choose a name for the controller class (e.g. SecurityController) [SecurityController]:

created: src/Security/LoginFormAuthenticator.php
updated: config/packages/security.yaml
created: src/Controller/SecurityController.php
created: templates/security/login.html.twig

This creates the login route, controller and template as well as a Guard authenticator that handles the login submit, includes CSRF protection and redirects intelligently on success and error. Your authenticator class will have a few minor TODOs inside (usually just 1) that you'll need to finish. But, you won't need to modify any config files.

The result? A fully functional login system in minutes that you have full control over. Customize the template to match your look and update the code in your authenticator to add anything special you need during the login process.

You can also generate a "empty" authenticator to use for whatever other authentication you need. Want support to generate other kinds of authenticators? Just open a pull request!

Happy security!


Be trained by Symfony experts - 2018-10-17 Paris - 2018-10-22 Clichy - 2018-10-22 Clichy
10/17/2018 08:24 am   Symfony Blog   Mirror   Link  

The international Symfony conference is coming in less than 2 months, on December 6th and 7th in the fantastic Lisbon, Portugal. Pre-conference workshops at SymfonyCon Lisbon are organized on December 4th and 5th and all of them are almost sold out! If you want to get trained before the conference, you might secure your workshop ticket before there are all gone!

We’re very pleased to announce that we have added a new workshop to the list:

Discover the Sylius plugin development with Symfony 4.1, one-day workshop. You will be trained by Sylius Core Team Members Mateusz Zalewski & Łukasz Chruściel. Learn all about how to implement a reusable plugin for your Sylius-based e-commerce application that will be crafted to your needs. We will use the most recent Symfony version, fulfilling its conventions and recommended practices. Using BDD methodology, we will not forget about tests that will describe your custom business logic and ensure us that we write clean and shiny code. During the workshop, we will be aiming to make plugin usable with Symfony Flex to make installation and configuration more developer-friendly.

You can combo this one-day workshop with the others one-day workshops already online but there are only a few seats left for the following workshops. Registration for these workshops is not available on both pre-conference workshop days as the workshops might already be sold out on selected dates:

  • Writing Modern JavaScript with Symfony & Webpack Encore by Ryan Weaver - Symfony Core Team member & docs leader (one-day workshop). In this workshop, we'll use the Webpack Encore library from Symfony to quickly bootstrap a sophisticated asset setup, complete with minification, SASS processing, automatic versioning, Babel support and everything you need to start writing great JavaScript quickly. We'll also learn about using JavaScript modules, how to bootstrap a framework (like React) and other important modern practices. Give your assets a huge boost with Webpack Encore!

  • Symfony 4 Best practices by Nicolas Grekas - Symfony Core Team member (one-day workshop). During this workshop, you will discover the new practices recommended by the Symfony Core Team. You will learn how to install third-party packages with Symfony Flex, configure your application with environment variables or exploit the new features of the dependency injection container. And much more! We'll build a demo app together so that you'll learn all the basic (and less basic) features that modern Symfony apps allow to build efficiently.

  • Symfony Messenger by Samuel Rozé - Symfony Core Team member and creator of the component (one-day workshop). The Messenger component just landed in Symfony 4.1. In this workshop, you will learn about: 1. Creating and handling messages as a strategy to decouple your application; 2. Configure the message routing and asynchronously handle your messages; 3. Discovering the bus middleware and creating your owns to add your custom logic; 4. An overview of using Messenger in the CQRS context (command and query buses); 5. Specifics of the AMQP and Enqueue adapters for your asynchronous processing; 6. How to customise and write your own adapters.

  • Building API-driven apps with API Platform by Kévin Dunglas - Symfony Core Team member (one-day workshop). After an overview of modern API patterns and formats (REST, Swagger, hypermedia, HATEOAS, JSON-LD, Hydra, Schema.org, GraphQL...), we'll learn how to use and extend the most popular features of the API Platform API component: Swagger documentation, pagination, validation, sorting, filtering, authentication, authorization, content negotiation, data model generation using the Schema.org vocabulary. Finally, we'll discover how easy it is to use the client-side (JavaScript) toolkit.

  • Mastering OOP & Design Patterns by Hugo Hamon - lead dev at Dayuse.com, ex head of training at SensioLabs (two-day workshop). Object Oriented Design aka OOD is hard and not limited to designing just classes and interfaces. This workshop will help you better understand all the concepts and techniques to write cleaner, more robust and more testable object oriented code. You'll learn how to make your code respect the SOLID principles. You'll also discover the techniques to reduce the complexity of your code as well as making your classes thinner and more focused. You'll also learn how to recognize and leverage the power of design patterns (factory, adapter, composite, decorator, mediator, strategy, etc.) in order to make your code flexible, extensible, unit testable and less fragile.

    Check out the entire workshop schedule and get your combo workshop and conference ticket now! See you soon at the conference in Lisbon!


Be trained by Symfony experts - 2018-10-17 Paris - 2018-10-22 Clichy - 2018-10-22 Clichy
10/16/2018 03:10 am   Symfony Blog   Mirror   Link