Home » Lists » Top 8 Useful Symfony Packages

Top 8 Useful Symfony Packages

Symfony is a popular framework for the PHP language that has its own dedicated composer plugins and bundles designed for use within the Symfony ecosystem. However, It can be challenging to integrate them into other projects. Fortunately, Symfony also has many simple independent packages that can be installed using composer in any project, making your code more readable, standardized, and faster.

In this article, I will list 8 useful Symfony packages which you can use in any project to make your code better.


Table of Contents

Top 8 Useful Symfony Packages

1. symfony/process

Sometimes you may need to run an external process from a PHP script. While you can use built-in PHP functions but they are not as convenient. This package is a great object-oriented wrapper for them. It provides a unified interface for all operating systems, can run processes asynchronously, and allows you to get output in real-time or after exit and check process exit code. You can install this package using the following command:

composer require symfony/process

After this, use this code to run your external process:

use Symfony\Component\Process\Process; $process = new Process(["/path/to/script.sh", "-option1", "-option2"]); $process->run(); // executes after the command finishes if ($process->isSuccessful()) { echo $process->getOutput(); } else { //Do something }

For example, let’s read contents from /proc/loadavg:

Also, you can get the output of the command in real-time by passing a closure into the run() method. For example:

use Symfony\Component\Process\Process; $process = new Process(["/usr/bin/watch", "/usr/bin/cat", "/proc/loadavg"]); $process->run(function ($type, $buffer) { echo $buffer; });

You can read more details how to use this package in the official documentation.

2. symfony/var-dumper

If you use Laravel, you may be familiar with the dd() or dump() functions which output the value of any variable in the command line or the browser. They are based on the symfony/var-dumper package, and, of course, you can use them in your projects even without Laravel. You can install symfony/var-dumper using this command:

composer require symfony/var-dumper

After this you can use dump() function in your code:

dump($someVar);

3. symfony/stopwatch

This is another package for debugging purposes. It helps measure execution time and memory consumption of your code. It can be done through PHP functions, but this package has more convenient interface. You can install it using this command:

composer require symfony/stopwatch

Example of using:

use Symfony\Component\Stopwatch\Stopwatch; $stopwatch = new Stopwatch(); $stopwatch->start('eventName'); // ... your code here $event = $stopwatch->stop('eventName'); echo (string) $event; //prints time in milliseconds and peak memory usage in MB as string echo $event->getMemory(); //prints peak memory usage echo $event->getDuration(); //prints execution time in milliseconds

4. symfony/dom-crawler

Browsers have an excellent API for interacting with DOM, finding elements on page, and changing their attributes. But sometimes you may want to have the same tools on backend. And you can with this package. It is not as easy as JQuery, but you can find elements by CSS selector or XPath expression, fetch their attributes or inner text and etc. Use this command to install the package:

composer require symfony/dom-crawler

The crawler expects to get an HTML code in constructor, so you should get it using file_get_contents(), Guzzle library, or load elsewhere. After this create a crawler instance:

use Symfony\Component\DomCrawler\Crawler; $html = <<<'HTML' <!DOCTYPE html> <html> <body> <p class="title">Hello From Haait</p> <p>Hello Crawler!</p> </body> </html> HTML; $crawler = new Crawler($html);

Now, you can find DOM nodes by CSS selector:

$nodeList = $crawler->filter('.title'); foreach($nodeList as $node){ echo $node->textContents; }

Also, you can use XPath expression:

$nodeList = $crawler->filterXPath('descendant-or-self::body/p'); foreach($nodeList as $node){ echo $node->textContents; }

You can get children, siblings, parent, node name, text and attributes for each node. Furthermore, you can add extra nodes and attributes. And finally, you can extract result HTML using this method:

$html = $crawler->html();

5. symfony/finder

If you need to list files or directories in filesystem, this package can be very helpful. It can search for files in multiple directories, filter them by name, type or contents, size, last modified or access date and etc. Supports sorting and excluding some items from results. Use this command to install the package:

composer require symfony/finder

Now, you can list all files in a directory:

use Symfony\Component\Finder\Finder; //.... $finder = new Finder(); $list = $finder->files()->in('/var/log/nginx/'); foreach($list as $file){ //Do something with \SplFileInfo object }

It utilizes the RecursiveDirectoryIterator class as a backed, so it is quite efficient. You can also limit the results to only *.php files. Note, that you should create a new instance of Finder for each request:

$finder = new Finder(); $list = $finder->files()->name('*.php');

Or you can limit the results to only directories. For example, you can get all directories in the project folder, but without subdirectories using the following code:

$finder = new Finder(); $list = $finder->directories()->in('./')->depth(0);

You can find more examples in the official documentation.

6. symfony/asset

This package provides a convenient way to generate URLs for your static assets, such as images, JS, and CSS files, etc. You can specify the base path and versioning strategy on the package initialization and it will automatically add this information to each asset. This package is already installed and used in Laravel, or you can Install it using the following command:

composer require symfony/asset

Now, you can create an instance of the UrlPackage class with necessary parameters. For example, the base path could be https://haait.net/public and the static version “v1”:

$package = new UrlPackage( 'https://haait.net/public', new StaticVersionStrategy('v1') );

And then, use this object to create URLs:

echo $package->getUrl('/logo.png'); echo $package->getUrl('/cover.png');

Laravel has the built-in asset() helper, which can do the same, but it can be useful in another environment.

7. symfony/filesystem

If you’re looking for an OOP wrapper to work with the file system instead of using built-in PHP functions, you can try the symfony/filesystem package. It allows to create directories and files, copy, move and rename them, and, of course, write content into files. You can install the package using this command:

composer require symfony/filesystem

Examples of using:

use Symfony\Component\Filesystem\Filesystem; $filesystem = new Filesystem(); if($filesystem->exists('/tmp/files/file.txt') === false){ $filesystem->touch('/tmp/files/file.txt'); } $filesystem->appendToFile('/tmp/files/file.txt', time());

This package does not have methods for retrieving the contents of files. But if you don’t want to use file_get_contents() you can use the SplFileInfo class which is used in the symfony/finder component. You can find more examples and documentation on the official page.

8. symfony/string

The PHP standard library contains multiple functions for working with ASCII strings and an extension which adds another set of functions for working with multi-byte Unicode strings. The symfony/string package provides a unified API for strings processing and offers a more convenient and object-oriented way to perform the same tasks as with the built-in functions. To Install the package, you can use the following command:

composer require symfony/string

After this, you can use classes and helpers from this library for your strings. For example:

$string = new UnicodeString("Haait"); echo $string->length(); //5 echo $string->lower(); //haait echo $string->upper(); //HAAIT echo $string->startsWith("Site"); //false echo $string->ensureStart("Site"); //Site Haait echo $string->indexOf("H"); //1

There are many other useful methods, which you can find in the official documentation.

Wrapping Up

In this article, I have highlighted 8 useful packages from Symfony, that I have used in my projects. These packages can save your time and enhance the quality of your project. Do you know other Symfony packages that can be useful? Please share their names in the comments section below.

Leave a Comment