Sling Academy
Home/PHP/PHP Doctrine: How to connect to PostgreSQL database

PHP Doctrine: How to connect to PostgreSQL database

Last updated: January 13, 2024

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.

Next Article: PHP Doctrine: How to connect to SQLite database

Previous Article: PHP Doctrine: How to connect to MySQL database

Series: Symfony & Doctrine Tutotirlas

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array