Database: Doctrine ORM
For developers who prefer a powerful Object-Relational Mapper (ORM), Rhapsody comes fully integrated with Doctrine. This allows you to work with your database using objects and entities, abstracting away raw SQL for more complex applications. This feature is available alongside the original PDO-based BaseModel, giving you the freedom to choose the right tool for your needs.
What are Entities?
In Doctrine, an "Entity" is a PHP class that maps directly to a database table. Each property in the class corresponds to a column in that table. All entity files should be placed in the app/Entities/ directory.
You define the mapping using PHP Attributes, which makes the configuration clean and readable.
Example: User Entity
<?php
namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'users')]
class User
{
#[ORM\Id]
#[ORM\Column(type: 'string', length: 255)]
private string $user_id;
#[ORM\Column(type: 'string', length: 50)]
private string $name;
// ... other properties
}
The Entity Manager
All interactions with the database in Doctrine are handled by the EntityManager. Rhapsody's service container is already configured to automatically build and inject the `EntityManager` into your controllers' constructors whenever you type-hint it.
use App\Entities\User;
use Doctrine\ORM\EntityManager; // Import the EntityManager
class AuthController extends BaseController
{
public function __construct(
protected EntityManager $em, // The container injects it here
protected Validator $validator,
Environment $twig
) {
parent::__construct($twig);
}
}
Fetching & Saving Data
Once the `EntityManager` is available in your controller (e.g., as $this->em), you can perform database operations.
Fetching Data
You can retrieve entities from the database using repositories.
// Find a single user by their email address
$user = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
// Find a user by their primary key
$user = $this->em->find(User::class, $userId);
Saving Data (Persisting)
To save a new entity or update an existing one, you use the persist() and flush() methods.
// Create a new User entity
$user = new User();
$user->setName('New User');
$user->setEmail('new@example.com');
$user->setPassword('a-secure-password');
// 1. Tell Doctrine to "manage" this new object
$this->em->persist($user);
// 2. Execute the INSERT query to save it to the database
$this->em->flush();