For quite some time now I had the plan to write about my two best friends when it comes to PHP development.
Symfony and PHPStorm
For many years I refused to use proprietary software for development... until I met Jetbrains, the company behind PHPStorm (and many more IDEs). There are many really great free IDEs out there like Netbeans or Eclipse or the more lightweight ones like GitHub's Atom or Adobe's Brackets. Back in my Windows days I even used Notepad++. So paying for an IDE doesn't really make sense, does it? At least that's what I thought for many years. Today I'm paying $10 a month for PHPStorm and believe me, It's worth every single penny.
However, this part of the series won't cover PHPStorm yet because I probably wouldn't be a paying customer without the great Symfony integration. This is why I want to explain Symfony first (Part 1+2) and then the advantages of using Symfony together with PHPStorm (Part 3). If I still have more to say then, maybe I'll write more parts.
This article is written from a Linux perspective. If you're on Windows, some things might be different.
Part 1: Symfony Components
As a PHP developer Symfony is my first choice for every webproject that's greater than a simple landingpage and needs to run some server-sided PHP code. Created by Fabien Potencier in 2005 it is now the most popular and modern PHP framework, powering some well-known projects like Drupal, phpBB, Piwik or even Composer... and a lot more. There are many good reasons to use Symfony.
If you've never heard of Symfony before the first thing you need to know is that Symfony is two things:
- A full-stack framework with everything a complex PHP project needs, ready to use
- A collection of independently usable tools for every imaginable purpose
This is why I use Symfony in some way or the other almost every time I do something in PHP. It's all about conventions and reusable code.
Another great thing about Symfony is it's really comprehensive documentation and the big and active community. With over 1.5k contributors only in the main repository, It's hard to not find any help when you need some. If you don't want to wait for part 2, covering the full framework (probably next week) you can start now by reading The Big Picture.
But now I want to start with the simplest way of using Symfony... Its many awesome components!
How to use a Symfony component
Symfony's components are not modules or plugins in the sense of something like a WordPress plugin, that only works with WordPress. The Symfony components are completely decoupled and independent of any framework. They are tools written in plain PHP following the standards for modern reusable code, defined by the PHP Framework Interop Group, which are known as PSR (PHP Standard Recommendations). Make yourself familiar with those standards, if you haven't already. Following standards and conventions paves the way for automation and reusability of code.
Now let's look at how to use a Symfony component in your project.
Composer
First you'll need Composer. Composer is the standard tool to install 3rd-party code (not only Symfony components) and define it as a dependency of your PHP project. You can even define the PHP version your project needs and more. If you haven't already, install it. I recommend installing it globally because you'll probably want to use it in all your future PHP projects. Just execute the following commands on the command line, to download, check and execute the installer and make Composer globally available:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
mv composer.phar /usr/local/bin/composer
Installing a component
Now that you have Composer installed, you can head over to the list of available Symfony components and choose one you want to try out. For convenience there's a dropdown and a copy button so you just have to paste the command on the command line and execute it.
One handy component I use very often is the Filesystem component.
composer require symfony/filesystem
Once this command has finished, this is what has happened:
- Comoposer created a directory called
vendor
inside the current directory. (This is where everything you install with composer lives in.) - It downloaded the files for the Filesystem component (to
vendor/symfony/filesystem/
). - It created two files, one called
composer.json
and the othercomposer.lock
You are now ready to use the Filesystem component but let me first explain the two files created by composer.
composer.json
If you take a look at this file you'll see this:
{
"require": {
"symfony/filesystem": "^3.3"
}
}
This is the most basic and simple version of a composer.json
file. All it does is to define one single dependency of your project. The ^3.3
constrains the version number to be at least 3.3 but below 4.0. You can control which versions to install quite precisely, when digging deeper into versions and constraints.
If there's an update for something you installed with composer, simply run the composer update
command and it will update according to the version constraints you defined for each dependency.
composer.lock
This file is what "locks" the exact installed version numbers. By defining a version number like above (^3.3), you'll get the latest version between 3.3.0 and 3.9.x when you run composer update
or the first time you run composer install
. The second time you run composer install
it won't look at composer.json
anymore but at composer.lock
, which holds the information about the exact version numbers that were installed the last time you invoked either composer install
or composer update
.
Just keep in mind:
composer install
usescomposer.json
when there is nocomposer.lock
composer update
always usescomposer.json
To install a project on a new server for example you want to use composer install
to get exactly what was working on your development machine. While developing you might want to use composer update
from time to time, to make your project work with the latest versions of your dependencies.
The autoloader
If you're still used to include
or require
files yourself, there's one last thing you have to get familiar with before we start. Autoloaders can do this for you automatically as long as the code that's to be included follows the PSR standard for autoloading (PSR-4), which is the case for almost everything you can install with composer.
If you want to learn more about autoloading you can read about it in the PHP docs. But in reality you don't have to worry about building your own autoloader. Composer generates one for you at vendor/autoload.php
. Simply require
it at the top of your PHP file.
<?php
require_once 'vendor/autoload.php';
Now all class files inside the vendor
direcotry will be included automatically once you try to use them. You can also add your own directories to the autoloader by specifying it in composer.json
:
{
"autoload": {
"psr-4": {"Acme\\": "src/"}
},
"require": {
...
}
}
This will autoload all classes from the Acme
namespace that live inside the src
directory of your project. (You have to run composer install
again to regenerate vendor/autoload.php
.)
Using the component (finally)
You can now use everything you've installed, without any further work. Getting to this point actually boils down to:
- one console command:
composer require symfony/filesystem
- one line of PHP:
require 'vendor/autoload.php';
Since you need to require the autoloader only once, it's actually just the Composer command to install and use a new Component.
Now let's have a look at the following examples to get an idea of how Symfony components can make your life much easier.
Filesystem
Command: composer require symfony/filesystem
<?php
require_once 'vendor/autoload.php';
$fs = new \Symfony\Component\Filesystem\Filesystem();
$filename = 'example.md';
if (!$fs->exists($filename)) {
$fs->touch($filename);
}
$fs->appendToFile($filename, "# My Content\n");
$fs->rename($filename, $filename . '.backup');
I think even without knowing PHP you can tell what is happening here. If the file example.md
does not exists, it will be created. Then some content is appended to the file and it gets renamed.
If you're now not amazed at all by the simplicity of this code, I can totally understand why. You might argue that this is easily doable with plain, native PHP code alone.
$filename = 'example.md';
if (!file_exists($filename)) {
touch($filename);
}
file_put_contents($filename, "# My Content\n", FILE_APPEND);
rename($filename, $filename . '.backup');
And indeed, this code does exactly the same... in fewer lines! But if you take a closer look at the Symfony methods, you'll notice that there's a lot more happening under the hood. Symfony checks constraints or specifics imposed by the operating system, it handles exceptions and common pitfalls for you and just does a lot of important stuff that you would normally don't even think about. If you're using a Symfony component, you're using very well tested and robust code! Keep that in mind, because this is what really adds value to your project!
Here are some other components I really like.
Finder
Command: composer require symfony/finder
<?php
...
$finder = new \Symfony\Component\Finder\Finder();
$finder->files()->in(__DIR__)->name('*.json');
foreach ($finder as $file) {
var_dump($file->getRealPath());
}
This outputs the path of all .json files inside the current directory. But the Finder component is much more powerful than what you can see here. You can filter files by name, type, size, date, directory or even content and it provides many handy methods to get the file information. If you need to handle files in your project, this component is such a relief!
Stopwatch
Very simple and self-explaining... a stopwatch to measure execution times.
Command: composer require symfony/stopwatch
<?php
...
$stopwatch = new \Symfony\Component\Stopwatch\Stopwatch();
$stopwatch->start('foo');
...
$event = $stopwatch->stop('foo');
var_dump($event->getDuration());
This outputs the execution time of everything between start
and stop
. You can also add "laps", get memory usage and more.
Process
Command: composer require symfony/process
<?php
...
$process = new Symfony\Component\Process\Process('ls -la');
$process->run();
if (!$process->isSuccessful()) {
throw new Symfony\Component\Process\Exception\ProcessFailedException($process);
}
echo $process->getOutput();
This runs the command ls -la
and outputs the results if the process doesn't fail. The Process component is way more powerful than I can show here. If you need to deal with the command line in your project, check out this component. You can even write your own commands with the Console component and run them using the process component.
Translation
Commands:
composer require symfony/translation
composer require symfony/yaml
(optional)
You can use this component without the Yaml component but I just think Yaml is a nice and clean way to store translation catalogues (or configuration) for your project. Symfony's Yaml component makes it easy to load and parse such files. However, you can also just use simple PHP arrays to store your translations.
<?php
...
$locale = 'de_DE';
$translator = new Symfony\Component\Translation\Translator($locale);
$translator->addLoader('yaml', new Symfony\Component\Translation\Loader\YamlFileLoader());
$translator->addResource('yaml', 'messages.en.yml', 'en_EN');
$translator->addResource('yaml', 'messages.de.yml', 'de_DE');
var_dump($translator->trans('some_translation_key'));
messages.en.yml
some_translation_key: Symfony is great!
messages.de.yml
some_translation_key: Symfony ist großartig!
This outputs a translated version of the string some_translation_key
based on the translations in messages.de.yml
and messages.en.yml
.
And these are really just a few simple components. There are many more available! Some are very simple, some others are quite enormous. Please check out the full list of available components and I'm pretty sure there's something you might want to use in a future project.
Imagine now that all these independent components were combined into a single, comprehensive PHP framework. Things like Routing, Templating, Security or Config are a part of almost every complex PHP application.
The Symfony full stack framework provides you with everything you need, right out of the box. This is also where PHPStorm enters the stage. But before we'll go into that, I will show you how to use the full stack framework no matter what IDE/editor you use.
Part 2: Symfony Full Stack

Interests:
Technology/Science/Future
Nature/Environment/Sustainability
Creativity/Programming
Check this out:
Steemit On Your Website
Steemit On Your Website