Architecture & DesignAccelerating PHP Web Application Creation with Symfony

Accelerating PHP Web Application Creation with Symfony

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

According to the World Wide Web Technology Surveys—a.k.a. W3Techs—site, PHP is the most popular server-side programming language by a wide margin, with 83.5% of Web sites using it for coding their server-side components. With so many projects being developed from scratch, you can bet that PHP was ripe for the framework treatment.

That’s where Symfony comes in. More than a mere framework, Symfony offers a set of PHP Components, a Web Application framework, a Philosophy, and a Community. You could say that it’s more of an ecosystem, really. It currently boasts over 3,000 contributors, 600,000 Symfony developers, and 48,000,000 monthly downloads. If you’ve got a few minutes, why not spend them exploring the Symfony universe with me here today as we build a simple Web page that incorporates a controller and route?

Setting Up the Framework

Before you install Symfony, you’ll want to verify that you’re using PHP 7.1 or higher. Most servers offer a utility for checking your server configuration, including the PHP version. You also can run this simple script that calls phpversion():

<?php
// Prints e.g. 'Current PHP version: 7.1.1'
echo 'Current PHP version: ' . phpversion();
?>

Symfony depends on the Composer PHP Dependency Manager. Be sure to install Composer globally on your system so that it’s part of your PATH.

If you want to use a virtual machine (VM), the Symfony team recommends Homestead.

Create your new project by running:

composer create-project symfony/website-skeleton my-php-project

This will create the my-php-project directory, download some dependencies into it, and generate the basic directories and files you’ll need to get started. It even offers helpful instructions on running, configuring, and testing your app:

Some files may have been created or updated to configure your new
   packages.
Please review, edit and commit them: these files are yours.

 What's next?

  * Run your application:
    1. Change to the project directory
    2. Create your code repository with the git init command
    3. Execute the php -S 127.0.0.1:8000 -t public command
    4. Browse to the http://localhost:8000/ URL.

       Quit the server with CTRL-C.
       Run composer require server --dev for a better web server.

  * Read the documentation at https://symfony.com/doc

 Database Configuration

  * Modify your DATABASE_URL config in .env

  * Configure the driver (mysql) and
    server_version (5.7) in config/packages/doctrine.yaml

 How to test?

  * Write test cases in the tests/ folder
  * Run php bin/phpunit

Symfony Project Structure
Figure 1: Symfony Project Structure

The website-skeleton project template is optimized for traditional Web applications. For building microservices, console applications, or APIs, you should set up the basic skeleton project.

Running Your Application

While in production, your application would run on a Web server like Nginx or Apache. For development, Symfony provides its own PHP Web server.

To run your app, cd into your new project and start the built-in server:

C:Usersblackjacques>cd my-php-project
C:Usersblackjacquesmy-php-project>php bin/console server:run

Once you see the “[OK] Server listening on http://127.0.0.1:8000” message, launch your browser and navigate to http://localhost:8000/. You then should see a welcome page, as depicted in Figure 2. To stop the server, press Ctrl+C from your terminal.

The welcome page
Figure 2: The welcome page

Creating a Web Page in Symfony

A Web page in Symfony is made up of two components:

  • A controller: The controller is the PHP function that serves content. It takes the incoming request information and uses it to create a Symfony Response object, which can hold HTML content, a JSON string, or even a binary file like an image or PDF.
  • A route: A route is the URL (e.g. /contact) to your page; it points to a controller.

Let’s create the above components in order.

The DateController

There’s a Symfony command to generate the controller for you. It will ask you for a name and take it from there:

C:Usersblackjacquesmy-php-project>php bin/console
   make:controller

 Choose a name for your controller class
   (e.g. GentlePizzaController):
 > DateController

 created: src/Controller/DateController.php
 created: templates/date/index.html.twig

  Success!

 Next: Open your new controller class and add some pages!

Now, we can make the DateController our own.

Open the file in your favorite text/PHP editor. You’ll see a fully functional controller:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;

class DateController extends AbstractController
{
    /**
     * @Route("/date/controller", name="date_controller")
     */
    public function index()
    {
        return $this->render('date_controller/index.html.twig', [
            'controller_name' => 'DateController',
        ]);
    }
}

Change the index() function to return an HTML Response instead:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;

class DateController extends AbstractController
{
    public function showDate()
    {
        return new Response(
            '<html><body><h1>Today is ' . date("Y/m/d") . '
               .</h1></body></html>'
        );
    }
}

The app_show_date Route

The route associates your controller function with a public URL (e.g. /show/date) so that the number() method is executed when a user browses to it. There are actually two ways to define a route:

The first is to create a route in the config/routes/routes.yaml file. If you haven’t defined any routes yet, you’ll have to create the routes.yaml file. Inside it, add the following info:

app_show_date:
   path: /show/date
   controller: AppControllerDateController::showDate

Instead of defining your route in YAML, Symfony also allows you to use annotation routes. It’s the recommended best practice. To use annotations, you’ll have to install the annotations package:

C:Usersblackjacquesmy-php-project>composer require annotations

You now can add your route directly above the controller:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;

class DateController extends AbstractController
{
    /**
    * @Route("/show/date")
    */
    public function showDate()
    {
        return new Response(
            '<html><body><h1>Today is ' . date("Y/m/d") . '
               .</h1></body></html>'
        );
    }
}

And that’s all there is to it. Using the Symfony Web server, as we did earlier, once again navigate to http://localhost:8000/show/date to see the page shown in Figure 3:

The Symfony Web server
Figure 3: The Symfony Web server

Conclusion

Although it may be a little premature to shout from the rooftop that Symfony is the PHP framework that we’ve been waiting for, I can say that it does have all of the ingredients of a winning framework thus far. In future articles, we’ll learn about the powerful Flex Composer plug-in, debugging your Symfony apps, and a whole lot more!

Rob Gravelle

Rob Gravelle resides in Ottawa, Canada. His design company has built Web applications for numerous businesses and government agencies. E-mail him.

Rob’s alter-ego, “Blackjacques,” is an accomplished guitar player, who has released several CDs and cover songs. His band, Ivory Knight, was rated as one of Canada’s top hard rock and metal groups by Brave Words magazine (issue #92).

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories