Symfony basics: what the framework gives you
What Symfony is
Symfony is two things at once: a set of independent PHP components (routing, console,
HTTP, mail and many more) and a framework that joins them into one project layout for building
web sites and JSON APIs. The components are used far outside Symfony itself: other PHP projects,
Laravel among them, are built on some of them.
It is open source, installed with Composer, and needs only PHP and a database to run.
If you know plain PHP, classes and
namespaces, you can start.
Main parts
Each part has its own lesson in the course.
- Routes: connect a URL and an HTTP method with the code that answers it. Lesson: Routes
- Controllers: classes that hold the logic of the pages. Lesson: Controllers
- Twig: the template language for HTML pages. Lesson: Twig basics
- Doctrine: the ORM: entities are plain classes, repositories load them. Lesson: Entities
- Migrations: database changes kept as PHP files in the project. Lesson: Migrations
- Forms and validation: build a form from a class and check the input with rules. Lesson: Forms
- Services: objects created by the container, which passes them their dependencies. Lesson: Services and DI
- Security: users, login and access rules. Lesson: Security intro
- Console: the command-line tool of the project, bin/console. Lesson: Console commands
- Messenger: moves slow work, such as sending mail, out of the request. Lesson: Messenger
How a request is handled
Every request enters through one file, public/index.php. Symfony turns it into a Request object and finds the route that matches the URL. The route calls a controller method. The controller gets the services it needs from the container, reads or changes data through Doctrine and returns a Response object: a Twig page for a browser or JSON for an API. Events fired on the way let other code step in, for example the security check.
What a project looks like
The main folders of a new project:
symfony-app/ ├── bin/ console ├── config/ settings, routes, services ├── migrations/ database changes ├── public/ index.php, the docroot ├── src/ controllers, entities, repositories ├── templates/ Twig templates ├── tests/ ├── var/ cache and logs ├── vendor/ packages installed by Composer └── .env settings of this machine
When to choose Symfony
Symfony is a good choice for:
- a large project that lives for years and is written by a team
- a project that needs strict structure: services, explicit configuration, typed entities
- a JSON API or a back end for a JavaScript front end
- a project that needs only some parts: each component installs on its own
For one static page or a small script a framework is more than you need: plain PHP is enough.
The other large PHP framework on this site is
Laravel.
Where to go next
Install the framework in lesson 2, Install Symfony, or see every lesson on the Symfony page.
Article author: Klavdiya Kondakova