PHP Doctrine: How to connect to PostgreSQL database

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

When working with PHP, interacting with databases is a common requirement, and using an Object-Relational Mapping (ORM) library can simplify the task. One of the most robust and popular ORMs for PHP is Doctrine. In this guide, we will walk through the steps involved in connecting a PostgreSQL database to a PHP application using Doctrine.

Prerequisites

  • PHP installed on your system.
  • Composer for managing dependencies.
  • PostgreSQL database server and credentials.

Setup Doctrine ORM using Composer

First, ensure you have Composer installed and then run the following command to install Doctrine:

composer require doctrine/orm

Database Connection Configuration

Now, set up the connection to PostgreSQL by configuring Doctrine’s EntityManager. Create a PHP file named bootstrap.php:

<?php

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

require_once "vendor/autoload.php";

$isDevMode = true;

// Configure connection parameters
$dbParams = [
    'driver' => 'pdo_pgsql',
    'user' => 'your_username',
    'password' => 'your_password',
    'dbname' => 'your_dbname',
    'host' => 'localhost',
    'port' => '5432'
];

$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
// Create EntityManager
$entityManager = EntityManager::create($dbParams, $config);

Replace ‘your_username’, ‘your_password’, and ‘your_dbname’ with your PostgreSQL credentials and target database respectively.

Creating Entity Classes

Doctrine uses entities to represent tables in your database. Here’s an example of an entity class representing a ‘users’ table:

<?php

namespace YourApp\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $username;

    // ... Getters and setters omitted for brevity
}

Each property of the class is annotated to map to a corresponding column in the ‘users’ table.

Performing Database Operations

With the entity and EntityManager set up, you can perform CRUD operations. Here’s how to insert a new user:

<?php

// bootstrap.php is assumed to have been included to setup $entityManager.

use YourApp\Entity\User;

$newUser = new User();
$newUser->setUsername('johndoe');

$entityManager->persist($newUser);
$entityManager->flush();

echo 'User with ID ' . $newUser->getId() . ' has been inserted.';

And here’s how you can fetch data:

<?php

// entityManager setup

$userRepository = $entityManager->getRepository('YourApp\Entity\User');
$user = $userRepository->find(1);

echo 'Username: ' . $user->getUsername();

Advanced Usage: QueryBuilder

Doctrines QueryBuilder allows for writing complex queries. Below is an example how to use it:

<?php

// entityManager setup

$queryBuilder = $entityManager->createQueryBuilder();
$query = $queryBuilder->select('u')
                   ->from('YourApp\Entity\User', 'u')
                   ->where('u.id = :id')
                   ->setParameter('id', 1)
                   ->getQuery();

$userFromQuery = $query->getSingleResult();

echo 'User is: ' . $userFromQuery->getUsername();

Conclusion

Integrating Doctrine with a PostgreSQL database in your PHP application streamlines database operations, offering a powerful layer of abstraction to work with database entities as if they were plain PHP objects. By understanding and leveraging the Doctrine ORM, PHP developers can greatly reduce the complexity of database interactions within their applications.