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.
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:
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:
That's it - now Symfony framework is configured to work with the database. In the next notes, we will consider specific examples.