A Repository is a design pattern that solves a common problem: the need to save a domain object and later reconstitute it.
A client provides the ID of the entity it wants to retrieve, and the repository takes the data for the corresponding entity from the database and finally reconstitutes the entire entity object using this data. If the repository can’t find an entity with the provided ID, it will return a null
value.
interface OrderRepository
{
public function save(Order $order): void;
public function ofId(int $orderId): ?Order;
}
Mapping entity data to table columns using an ORM
We need to map the entity data to table columns to write the implementation that saves an entity to the database.
The most common option is to use an ORM.
If, for example, we use Doctrine ORM, we need to add mapping configuration to the entity class and its properties. We can do that using annotations, so Doctrine should be able to save the object’s data in the right table and columns.
use Doctrine\ORM\Mapping as ORM;
/∗∗
∗ @ORM\Entity
∗ @ORM\Table(name="orders")
∗/
final class Order
{
/∗∗
∗ @ORM\Id
∗ @ORM\Column(type="integer")
∗/
private int $id;
/∗∗
∗ @ORM\Column(type="string")
∗/
private string $emailAddress;
/∗∗
∗ @ORM\Column(type="int")
∗/
private int $quantityOrdered;
/∗∗
∗ @ORM\Column(type="int")
∗/
private int $pricePerUnitInCents;
// ...
}
We can now write a very straightforward implementation of the OrderRepository
interface, which uses Doctrine’s EntityManager
to persist Order objects.
use Doctrine\ORM\EntityManagerInterface;
final class OrderRepositoryUsingDoctrineOrm implements OrderRepository
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this−>entityManager = $entityManager;
}
public function save(Order $order): void
{
$this−>entityManager−>persist($order);
$this−>entityManager−>flush();
}
}
How is Doctrine able to get the data out of the entity? It uses reflection ⤴️ to reach the object, copy the data from its private properties, and prepare the desired array.