Reading From SQL Server with Symfony

After you have installed Symfony and configured the database connection, you will want to write some code to retrieve data from the database.

Install Doctrine

The first step involves installing the Doctrine library to map your database. To do so, open a command prompt and navigate to your project directory. Then enter the following installation command:


composer require doctrine/doctrine-bundle


You should eventually get a message saying all assets were successfully installed.

Finally, enable the bundle by adding the following to the $bundles array inside the registerBundles function in the app/AppKernel.php file:


new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),


Create a Class for Your Data

Next you will need to create a class (aka entity) to map and hold the data from your database.

Create an Entity folder inside src/AppBundle. Within that folder create a class file (ex. Employee.php) with the following code:


namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

* @ORM\Entity
* @ORM\Table(name=”tablelNameGoesHere”)

class Employee {
* @ORM\Column(type=”integer”)
private $ID;

* @ORM\Column(type=”nvarchar”, length=255)
private $FIRST_NAME;

* @ORM\Column(type=”nvarchar”, length=255)
private $LAST_NAME;


Note that you will want to change your field names and data types to match the database you are using.

Also note that instead of using the PHP annotations above, you could use YAML or XML as explained in this Symfony Doctrine page.

In a subsequent post, I will describe how to read and display data.