in symfony, Uncategorized

Advanced Symfony 2 environment variables

In this article I’m going to share a trick that I use to achieve a similar result of the New in Symfony 3.4: Advanced environment variables for Symfony 2.x.

The new advanced environment variables is a great improvement on the developer experience using symfony. It is the way to go in the future and it expands what you can do using YML thanks to Symfony Expressions in the config and parameter files. Although you could do exactly the same in Symfony 2 with a small little trick.

Advanced Symfony 2 environment variables example

imports:
    - { resource: parameters.yml }
    - { resource: parameters.php }

This is the real case scenario:

  • Manual testing environment on AWS Beanstalk
  • Code ready to go to production with different environment variables
  • Mailcatcher for emails
  • AWS Beanstalk can’t have empty vars, it just remove them from the admin panel
  • Swiftmailer does not accept empty string as null encryption, null username and null password
<?php
/**
 * Convert "" into null for swift mailer
 *
 * AWS Beanstalk delete null ENV VARS so the only way of adding an empty ENV VAR is leaving it empty
 *  which symfony process as ""
 *
 * Swiftmailer does not accept "" as none encryption and for that case it has to be null
 *
 */

$mailerEncryptionPlaceholder=$container->getParameter("mailer_encryption");
$mailerEncryption=$container->getParameterBag()->resolveValue($mailerEncryptionPlaceholder);
if(strlen(trim($mailerEncryption))==0||$mailerEncryption=="none") {
    $container->setParameter("mailer_encryption", null);
}

$mailerUserPlaceHolder=$container->getParameter("mailer_user");
$mailerUser=$container->getParameterBag()->resolveValue($mailerUserPlaceHolder);
if(strlen(trim($mailerUser))==0||$mailerUser=="none") {
    $container->setParameter("mailer_user", null);
}

$mailerPasswordPlaceholder=$container->getParameter("mailer_password");
$mailerPassword=$container->getParameterBag()->resolveValue($mailerPasswordPlaceholder);
if(strlen(trim($mailerPassword))==0||$mailerPassword=="none") {
    $container->setParameter("mailer_password", null);
}

Conclusion

The new Symfony 3.4 feature that allows to use advanced environment variables is really convenient. It will be more readable, easy to follow and they have a great example on how to store secrets.

For the ones you have not had time to migrate to Symfony 3 you can use Symfony 2 advanced environment variables with a simple and plain PHP file.

Please add your tricks and questions on the comments.

Write a Comment

Comment