What is Symfony

Symfony is an Open Source PHP framework for web applications and a set of reusable PHP components. It was originally conceived in 2005 by the interactive agency SensioLabs for the development of web sites for its own customers.

Thousands of web sites and applications rely on Symfony as the Foundation of their web services. And most of the leading PHP projects, such as Drupal and Laravel use Symfony components to build their applications.

Why is Symfony better than just opening up a file and writing flat PHP?

If you’ve never used a PHP framework, aren’t familiar with the Model-View-Controller (MVC) philosophy, or just wonder what all the hype is around Symfony, this article is for you. Instead of telling you that Symfony allows you to develop faster and better software than with flat PHP, you’ll see for yourself.

In this article, you’ll write a simple application in flat PHP, and then refactor it to be more organized. You’ll travel through time, seeing the decisions behind why web development has evolved over the past several years to where it is now.

By the end, you’ll see how Symfony can rescue you from mundane tasks and let you take back control of your code.

A Simple Blog in Flat PHP

In this article, you’ll build the token blog application using only flat PHP. To begin, create a single page that displays blog entries that have been persisted to the database. Writing in flat PHP is quick and dirty:

// index.php
$connection = new PDO("mysql:host=localhost;dbname=blog_db", 'myuser', 'mypassword');

$result = $connection->query('SELECT id, title FROM post');

<!DOCTYPE html>
        <title>List of Posts</title>
        <h1>List of Posts</h1>
            <?php while ($row = $result->fetch(PDO::FETCH_ASSOC)): ?>
                <a href="/show.php?id=<?= $row['id'] ?>">
                    <?= $row['title'] ?>
            <?php endwhile ?>

$connection = null;

That’s quick to write, fast to execute, and, as your app grows, impossible to maintain. There are several problems that need to be addressed:

  • No error-checking: What if the connection to the database fails?
  • Poor organization: If the application grows, this single file will become increasingly unmaintainable. Where should you put code to handle a form submission? How can you validate data? Where should code Go for sending emails?
  • Difficult to reuse code: Since everything is in one file, there’s no way to reuse any part of the application for other “pages” of the blog.