Introduction to Symfony
Installation of Symfony framework
Prerequisites
First, in order to start a new project in Symfony, you'll need to install the CLI (command line interpreter of the project). Before that,
you can verify that you still have php and composer installed and with a right version.
As always, to check the version of a package, use
php -v ## short for --version
and
composer --version ## short fort --version
If any of those packages are missing, please refer to their official documentation to install them, that you'll find for php here and
for compose here.
Install Symfony CLI
Now, you can install Symfony CLI through your laptop package installer. As always, you can refer to the official documentation
right here.
For macOS users, type
brew install symfony-cli/tap/symfony-cli
For Debian/Ubuntu users (yes this work if you use the windows subsytem for linux):
curl -1sLf 'https://dl.cloudsmith.io/public/symfony/stable/setup.deb.sh' | sudo -E bash
sudo apt install symfony-cli
Since version 4 of the Symfony framework, there is no official distribution anymore.
The vision of the team that maintains the project is to provide lightweight application skeletons, and to let developers decide
which dependencies are needed in their applications.
For now one, we will use the website-skeleton, used, you guessed it, mostly for websites.
There is two ways to create a project through this package:
With Symfony CLI:
symfony new --webapp mySymfonyProject
With Composer:
composer create-project symfony/website-skeleton mySymfonyProject
Your project is now created ! Before getting to the heart of the matter, think about initialize a git repository.
Enter in your project and init the repository through:
cd mySymfonyProject; git init
Now, add the remote origin to a blank repository on github with
git remote add origin <git SSH URL>
Now, you're ready to launch your project. To do that, just type:
symfony server:start
Creating your first page
Route and Controller
First of all, we'll learn how to create your trainer profile. So create a file that generates a trainer license number and prints it. To do
that, create a "Controller" class and a "controller" method inside of it.
You'll create the controller under src/Controller/TrainerController.php
Now you need to associate this controller function with a public URL (e.g. /trainer/license) so that the number() method is called
when a user browses to it. This association is defined by creating a route in the config/routes.yaml file.
If you are using Symfony web server, try it out by going to: http://localhost:8000/trainer/license
Rendering through templates
If you're returning HTML from your controller, you'll probably want to render a template. As we said previously, Symfony comes
with a template rendering engine, called Twig.
To use twig templates within a controlled, you'll first need to make sure that TrainerController extends Symfony's base
AbstractController class:
// src/Controller/LuckyController.php
// ...
+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- class TrainerController
+ class TrainerController extends AbstractController
{
// ...
}
You can now use the render method inside your controller to display as previously your license number.
Template files live in the templates/ directory, which was created for you automatically when you installed Twig. Create a new
templates/trainer directory with a new license.html.twig file inside.
Playing with Request / Response
The Symfony framework, and especially its HttpFoundation component, provides an abstraction layer for the request and the
response, easy to use and to handle.
The Request class allows to centralize the access to all PHP super variables in a single utility class, while the Response class
allows to return a response to the user valid in terms of HTTP language.
example:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals();
$name = $request->get('name');
$response = new Response();
$response->setContent(
'Hello'
. $name
.''
);
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'text/html');
$response->send();
Routing
The responsibility of binding a URL to a PHP action is done by the Routing component which is available in the framework The
Routing component is very powerful and supports many declaration formats: PHP, of course, but also XML, YAML or annotations
which is the recommended format we will use from now on.
Here an example from symfony documentation of how to use Routes with annotation for a CRUD based controller
// src/Controller/ApiController.php
namespace App\Controller;
// ...
class ApiController extends AbstractController
{
#[Route('/api/posts/{id}', methods: ['GET', 'HEAD'])]
public function show(int $id): Response
{
// ... return a JSON response with the post
}
#[Route('/api/posts/{id}', methods: ['PUT'])]
public function edit(int $id): Response
{
// ... edit a post
}
}
Setting up the Database with Doctrine
First, install Doctrine support via the orm Symfony pack, as well as the MakerBundle, which will help generate some code:
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle
The database connection information is stored as an environment variable called DATABASE_URL. For development, you can find
and customize this inside .env:
DATABASE_URL="mysql://root:root@127.0.0.1:8889/poke_db?serverVersion=5.7"
This is a working example for MAMP stack. To create the database, just type
php bin/console doctrine:database:create
You can now create an entity, or field in your database. Try taping
php bin/console make:entity
and create a first Pokemon entity ! It should have at least a name, a number, and types.
Working with API
Now that you have basics elements to start a symfony project, try to take a look at the PokeAPI
And try to get a json response from https://pokeapi.co/api/v2/pokemon