Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Meet Symfony

Symfony is a framework for projects that live for years: online shops, business systems, APIs. It consists of independent components, and many of them work inside other projects — Laravel included. Symfony is stricter than Laravel: more explicit types and configuration, less "magic".

Creating a project

You need PHP 8.2 or newer and Composer:

composer create-project symfony/skeleton blog
cd blog
composer require webapp

The first command creates a minimal project; composer require webapp adds everything for a regular site: templates, forms, database access, security.

Running

php -S localhost:8000 -t public

Open http://localhost:8000 — the Symfony welcome page appears. If the Symfony CLI program is installed, the server is started with symfony server:start.

Project structure

FolderWhat is in it
src/ControllerControllers — request handlers
src/EntityEntities — data classes
templatesTwig templates
configSettings
publicThe web root: index.php, images
varCache and logs
migrationsChanges to the database structure

The .env file holds values that depend on the environment: the database address, the mode.

The first page

A controller is a class whose method receives a request and returns a response. The #[Route] attribute sets the address:

// src/Controller/HomeController.php
namespace App\Controller;
 
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
 
class HomeController
{
    #[Route('/')]
    public function index(): Response
    {
        return new Response('<h1>Hello, Symfony!</h1>');
    }
}

Save the file and refresh the page. Nothing needs registering: Symfony finds classes in the src folder by itself.

The console

The bin/console command is the developer's main tool:

php bin/console list
php bin/console debug:router
php bin/console make:controller BlogController

debug:router shows every route; the make: commands generate class skeletons.

The debug toolbar

In development mode every page has a toolbar at the bottom: response time, database queries, the route, the log. Clicking it opens the profiler with the details of the request. It is the first place to look when something misbehaves.

Common mistake

The web root is the public folder, not the project folder. If the web server points at the project itself, visitors can open the .env file with passwords. On a server always set public as the root folder.

Thanks for reading!

Donate to the site — we work hard for you.