10 Commands to Add a Database to Symfony

Coding (Symfony)

Jan 23, 2023

The Beginner-friendly tutorial about Doctrine, Symfony and databases
 
/img/blog/how-to-add-a-database-to-symfony.jpeg

Data is a staple of any web application.

The vast majority of software we use daily connects to a database of some sort.

In this article, I’ll show 10 easy commands to create a Symfony project and add a database to your application in just a few minutes.

 

Download Symfony

Symfony is one of the most popular PHP frameworks available currently.

It is very lightweight and easy to use.

To start using it you only need to run a few commands:

 

Command #1: 

symfony check:requirements

 

This command will check if your system has the correct requirements for making Symfony work.

If you receive a positive response it is time to download the packages.

 

Command #2:

symfony new myApp — version=”6.2.*” — webapp 

 

The command above will download all the files from the Symfony repository.

That is all! 

From this point, you can already use your application by starting the server.

 

Commands #3 and #4:

cd myApp/
symfony server:start

 

Install Doctrine

Consider Doctrine as a set of libraries that save time and hassles from the developer’s workload.

It contains many amazing packages such as an ORM and a Database Abstraction Layer.

Installing Doctrine is as easy as installing Symfony.

To do so we only need to use 2 commands.

 

Commands #5:

composer require symfony/orm-pack

 

This will install the object-relational mapper on our application.

What is an ORM?

It is an amazing feature that ‘transforms’ the data coming from the database to an object.

This gives us many advantages.

As an object, the mother class has a ton of methods we can take advantage of.

 

Commands #6:

composer require — dev symfony/maker-bundle

 

Symfony is famous for its bundles.

Those are packages that make your life easier.

There are dozens of these bundles available to us.

On this occasion, the bundle of choice is Maker.

It will create entities that will be reproduced into the database.

 

 

 

 

Basic Configurations

For an application needing a database, we need to know where this application needs to connect to.

To do so we should update the environment variables that describe how to connect.

Those variables are set in the .env file (at the root of our new application).

We can use different types of databases, MySql is the most used but we can also opt for MariaDB, SQLite, Postgres, or Oracle.

To use one of them uncomment the line and update the values:

 

DATABASE_URL=”mysql://username:[email protected]:port/database_name"

Be careful because if any of these values contain one or more special characters, you must encode them.

 

Commands #7:

php bin/console doctrine:database:create 

 

If the values you update are correct you should see a success message and a new database showing up on your machine.

 

Create Entities

Entities are classes that describe how a table should look inside your database.

In other PHP frameworks, these classes are called models.

To create entities we need to use the bundle we installed before.

We do it by using the following command.

 

Commands #8:

php bin/console make:entity

 

This will tell our application to create a new class of type entity and to prompt all the information needed.

 

Class name of the entity to create or update:
> User

New property name (press  to stop adding fields):
> name

Field type (enter ? to see all types) [string]:
> string

Field length [255]:
> 255

Can this field be null in the database (nullable) (yes/no) [no]:
> no

New property name (press  to stop adding fields):
> email

Field type (enter ? to see all types) [string]:
> string

Can this field be null in the database (nullable) (yes/no) [no]:
> no

New property name (press  to stop adding fields):
>
(press enter again to finish)

 

This info is, the name of the class and what fields are required.

Once done, The new class will be automatically created and it will be complete of setters and getters.

Here is an example:

 

// src/Entity/User.php
namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;

 #[ORM\Entity(repositoryClass: UserRepository::class)]
class User
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private int $id;

    #[ORM\Column(length: 255)]
    private string $name;

    #[ORM\Column(length: 255)]
    private string $email;
        
    public function getId(): ?int
    {
        return $this->id;
    }

    // ... getter and setter methods
}

 

Migrate

What we have done so far is create a database using the information we set in the .env file.

Then we created an entity describing how the User table should look like.

Notice that we do not have any tables in our database yet.

The process of transferring the information from our PHP entity class to the inside of our database is called migration.

To ‘activate’ the migration we run the following commands.

 

Command #9:

php bin/console make:migration 

 

This will create a new file inside the migrations folder.

Inside the file, there are all the SQL queries needed to create the User table and its fields.

To run those queries we need to enter the last command of the article.

 

Commands #10:

php bin/console doctrine:migrations:migrate

 

This above is the command that actually executes the migration.

You should now be able to see the User table and the id, name, and email field on your database.

If you want to update the table or add new fields to it you just need to run commands #8, #9, and #10 again adding your new details.

 

Conclusion

Pretty easy right?

As we have just seen Symfony makes it incredibly straightforward to create a brand-new application and connect it to a database.

In the next article will see how to save and retrieve data into and from it.

If that was a bit too advanced for you, read the basics of PHP now

Also, if you liked this easy-to-read tutorial subscribe to my newsletter and be notified when the next part is coming.

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Symfony) Jan 11, 2023

How to Create a Page in Symfony 6 (Frontend)?

See details
Coding (Symfony) Feb 7, 2023

How to add forms in Symfony 6

See details
Get my free books' review to improve your skill now!
I don't want to improve