Env local php symfony

The Dotenv Component

Warning: You are browsing the documentation for Symfony 4.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.3 (the current stable version).

The Dotenv Component

The Dotenv Component parses .env files to make environment variables stored in them accessible via $_ENV or $_SERVER .

Installation

$ composer require symfony/dotenv

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Usage

Sensitive information and environment-dependent settings should be defined as environment variables (as recommended for twelve-factor applications). Using a .env file to store those environment variables eases development and CI management by keeping them in one «standard» place and agnostic of the technology stack you are using (nginx vs PHP built-in server for instance).

PHP has a lot of different implementations of this «pattern». This implementation’s goal is to replicate what source .env would do. It tries to be as similar as possible with the standard shell’s behavior (so no value validation for instance).

Load a .env file in your PHP application via Dotenv::load() :

use Symfony\Component\Dotenv\Dotenv; $dotenv = new Dotenv(); $dotenv->load(__DIR__.'/.env'); // You can also load several files $dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');

Given the following .env file content:

# .env DB_USER=root DB_PASS=pass

Access the value with $_ENV in your code:

$dbUser = $_ENV['DB_USER']; // you can also use ``$_SERVER``

The load() method never overwrites existing environment variables. Use the overload() method if you need to overwrite them:

As you’re working with the Dotenv component you’ll notice that you might want to have different files depending on the environment you’re working in. Typically this happens for local development or Continuous Integration where you might want to have different files for your test and dev environments.

You can use Dotenv::loadEnv() to ease this process:

use Symfony\Component\Dotenv\Dotenv; $dotenv = new Dotenv(); $dotenv->loadEnv(__DIR__.'/.env');

The Dotenv component will then look for the correct .env file to load in the following order whereas the files loaded later override the variables defined in previously loaded files:

  1. If .env exists, it is loaded first. In case there’s no .env file but a .env.dist , this one will be loaded instead.
  2. If one of the previously mentioned files contains the APP_ENV variable, the variable is populated and used to load environment-specific files hereafter. If APP_ENV is not defined in either of the previously mentioned files, dev is assumed for APP_ENV and populated by default.
  3. If there’s a .env.local representing general local environment variables it’s loaded now.
  4. If there’s a .env.$env.local file, this one is loaded. Otherwise, it falls back to .env.$env .
Читайте также:  Java set contains any

This might look complicated at first glance but it gives you the opportunity to commit multiple environment-specific files that can then be adjusted to your local environment. Given you commit .env , .env.test and .env.dev to represent different configuration settings for your environments, each of them can be adjusted by using .env.local , .env.test.local and .env.dev.local respectively.

.env.local is always ignored in test environment because tests should produce the same results for everyone.

You can adjust the variable defining the environment, default environment and test environments by passing them as additional arguments to Dotenv::loadEnv() (see loadEnv() for details).

The Dotenv::loadEnv() method was introduced in Symfony 4.2.

You should never store a .env.local file in your code repository as it might contain sensitive information; create a .env file (or multiple environment-specific ones as shown above) with sensible defaults instead.

Symfony Dotenv can be used in any environment of your application: development, testing, staging and even production. However, in production it’s recommended to configure real environment variables to avoid the performance overhead of parsing the .env file for every request.

As a .env file is a regular shell script, you can source it in your own shell scripts:

Add comments by prefixing them with # :

# Database credentials DB_USER=root DB_PASS=pass # This is the secret password

Use environment variables in values by prefixing variables with $ :

DB_USER=root DB_PASS=$ pass # Include the user as a password prefix

The order is important when some env var depends on the value of other env vars. In the above example, DB_PASS must be defined after DB_USER . Moreover, if you define multiple .env files and put DB_PASS first, its value will depend on the DB_USER value defined in other files instead of the value defined in this file.

Embed commands via $() (not supported on Windows):

Note that using $() might not work depending on your shell.

Источник

How to Deploy a Symfony Application

Deploying a Symfony application can be a complex and varied task depending on the setup and the requirements of your application. This article is not a step-by-step guide, but is a general list of the most common requirements and ideas for deployment.

Symfony Deployment Basics

The typical steps taken while deploying a Symfony application include:

  1. Upload your code to the production server;
  2. Install your vendor dependencies (typically done via Composer and may be done before uploading);
  3. Running database migrations or similar tasks to update any changed data structures;
  4. Clearing (and optionally, warming up) your cache.

A deployment may also include other tasks, such as:

  • Tagging a particular version of your code as a release in your source control repository;
  • Creating a temporary staging area to build your updated setup «offline»;
  • Running any tests available to ensure code and/or server stability;
  • Removal of any unnecessary files from the public/ directory to keep your production environment clean;
  • Clearing of external cache systems (like Memcached or Redis).

How to Deploy a Symfony Application

There are several ways you can deploy a Symfony application. Start with a few basic deployment strategies and build up from there.

Basic File Transfer

The most basic way of deploying an application is copying the files manually via FTP/SCP (or similar method). This has its disadvantages as you lack control over the system as the upgrade progresses. This method also requires you to take some manual steps after transferring the files (see Common Deployment Tasks).

Using Source Control

If you’re using source control (e.g. Git or SVN), you can simplify by having your live installation also be a copy of your repository. When you’re ready to upgrade, fetch the latest updates from your source control system. When using Git, a common approach is to create a tag for each release and check out the appropriate tag on deployment (see Git Tagging).

This makes updating your files easier, but you still need to worry about manually taking other steps (see Common Deployment Tasks).

Using Platforms as a Service

Using a Platform as a Service (PaaS) can be a great way to deploy your Symfony app quickly. There are many PaaS, but we recommend Platform.sh as it provides a dedicated Symfony integration and helps fund the Symfony development.

Using Build Scripts and other Tools

There are also tools to help ease the pain of deployment. Some of them have been specifically tailored to the requirements of Symfony.

Deployer This is another native PHP rewrite of Capistrano, with some ready recipes for Symfony. Ansistrano An Ansible role that allows you to configure a powerful deploy via YAML files. Magallanes This Capistrano-like deployment tool is built in PHP, and may be easier for PHP developers to extend for their needs. Fabric This Python-based library provides a basic suite of operations for executing local or remote shell commands and uploading/downloading files. Capistrano with Symfony plugin Capistrano is a remote server automation and deployment tool written in Ruby. Symfony plugin is a plugin to ease Symfony related tasks, inspired by Capifony (which works only with Capistrano 2).

Common Deployment Tasks

Before and after deploying your actual source code, there are a number of common things you’ll need to do:

A) Check Requirements

There are some technical requirements for running Symfony applications. In your development machine, the recommended way to check these requirements is to use Symfony CLI. However, in your production server you might prefer to not install the Symfony CLI tool. In those cases, install this other package in your application:

$ composer require symfony/requirements-checker

Then, make sure that the checker is included in your Composer scripts:

1 2 3 4 5 6 7 8 9 10 11 12
< ". ": ". ", "scripts": < "auto-scripts": < "vendor/bin/requirements-checker": "php-script", ". ": ". " >, ". ": ". " > >

B) Configure your Environment Variables

Most Symfony applications read their configuration from environment variables. While developing locally, you’ll usually store these in .env and .env.local (for local overrides). On production, you have two options:

  1. Create «real» environment variables. How you set environment variables, depends on your setup: they can be set at the command line, in your Nginx configuration, or via other methods provided by your hosting service;
  2. Or, create a .env.local file like your local development.

There is no significant advantage to either of the two options: use whatever is most natural in your hosting environment.

You might not want your application to process the .env.* files on every request. You can generate an optimized .env.local.php which overrides all other configuration files:

The generated file will contain all the configuration stored in .env . If you want to rely only on environment variables, generate one without any values using:

$ composer dump-env prod --empty

If you don’t have Composer installed on the production server, use instead the dotenv:dump Symfony command.

C) Install/Update your Vendors

Your vendors can be updated before transferring your source code (i.e. update the vendor/ directory, then transfer that with your source code) or afterwards on the server. Either way, update your vendors as you normally do:

$ composer install --no-dev --optimize-autoloader

The —optimize-autoloader flag improves Composer’s autoloader performance significantly by building a «class map». The —no-dev flag ensures that development packages are not installed in the production environment.

If you get a «class not found» error during this step, you may need to run export APP_ENV=prod (or export SYMFONY_ENV=prod if you’re not using Symfony Flex) before running this command so that the post-install-cmd scripts run in the prod environment.

D) Clear your Symfony Cache

Make sure you clear and warm-up your Symfony cache:

$ APP_ENV=prod APP_DEBUG=0 php bin/console cache:clear

E) Other Things!

There may be lots of other things that you need to do, depending on your setup:

  • Running any database migrations
  • Clearing your APCu cache
  • Add/edit CRON jobs
  • Restarting your workers
  • Building and minifying your assets with Webpack Encore
  • Compile your assets if you’re using the AssetMapper component
  • Pushing assets to a CDN
  • On a shared hosting platform using the Apache web server, you may need to install the symfony/apache-pack package
  • etc.

Application Lifecycle: Continuous Integration, QA, etc.

While this article covers the technical details of deploying, the full lifecycle of taking code from development up to production may have more steps: deploying to staging, QA (Quality Assurance), running tests, etc.

The use of staging, testing, QA, continuous integration, database migrations and the capability to roll back in case of failure are all strongly advised. There are simple and more complex tools and one can make the deployment as easy (or sophisticated) as your environment requires.

Don’t forget that deploying your application also involves updating any dependency (typically via Composer), migrating your database, clearing your cache and other potential things like pushing assets to a CDN (see Common Deployment Tasks).

Troubleshooting

Deployments not Using the composer.json File

The project root directory (whose value is used via the kernel.project_dir parameter and the getProjectDir() method) is calculated automatically by Symfony as the directory where the main composer.json file is stored.

In deployments not using the composer.json file, you’ll need to override the getProjectDir() method as explained in this section.

Learn More

Источник

Оцените статью