Working with databases in the Symfony framework. Introduction (Lesson 9. Getting acquainted with Doctrine)

We are no longer children, we already know how to work with controller, configure routing system for handling input data by the controller, and create view. The next logical step will be learning working with databases in Symfony framework using Doctrine as an example.This note is introductory, but still we need to mention some things from the very beginning, which will be very useful for further studying Doctrine. So, first of all, it would be very convenient if the existing tables (if you already have a designed database, I recommend this option, although I will describe the possibility of creating a database after designing its model) should be of type InnoDB. If you previously created MyISAM tables, you can read about how to convert them here. InnoDB is necessary for creating relationships (foreign key) between tables.

Symfony framework uses a popular method for working with databases today through ORM - Object-relational mapping. The essence is that an abstract layer is created between the database and the programmer. Now there is no need to write queries directly to the database, it is enough to interact with this layer. This creates several advantages. Firstly, the code becomes simpler and shorter. Secondly, it automatically eliminates errors when designing queries, or even automatic or customizable validation. And probably one of the main advantages is that you do not need to know the features of a specific DBMS - you only need to know the interface for working with the abstract layer, everything else will be done for you.

DB ORM

First, you need to configure Symfony framework to work with the database. By default, the config is located at app/config/parameters.yml. The location can be changed to any (if it is more convenient for you, the file parameters are connected in the file app/config/config.yml). The contents of app/config/parameters.yml:

parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: null
    database_name: symfony
    database_user: root
    database_password: pass
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: ru
    secret: 9a78eae13ab2ced383f3124a3e607c9f31e7f3e8
    database_path: null
I hope the config is self-explanatory - we set the database type (MySQL in my case), and also the connection parameters - host, user, password.

If you want to use SQLite, you need to specify the location of the file in the parameters:

# app/config/config.yml
doctrine:
  dbal:
    driver: pdo_sqlite
    path: "%kernel.root_dir%/sqlite.db"
    charset: UTF8
That's it - now Symfony framework is configured to work with the database. In the next notes, we will consider specific examples.