Object-Relational Mappers
Learn how to translate model entities into database records using object-relational mappers.
We'll cover the following...
SQL provides a powerful tool for querying data, but the records we get in the result are just plain key-value arrays with scalar values inside. Also, we have to write SQL commands to update and query data. That’s database-specific logic, and we might want to keep it separate from application logic.
When we query theater plays from the database, we want to retrieve an array of Play
objects instead of plain arrays. In this case, we can be sure of our data structure and use the Play
class methods. When we update a play, we usually want to update some properties in the Play
object instead of composing an SQL command.
We can solve this with an object-relational mapper (ORM), an abstraction layer that translates data between our objects and the database. To developers, ORMs seem like magical databases that understand our objects. And, it uses the actual database in the background.
The most popular ORM in PHP according to the Packagist repository is Doctrine ORM. This lesson was mostly written with Doctrine in mind. Things might be slightly different with other ORMs.
How ORM works
Every ORM consists of a data mapper and an application interface. A data mapper is a component that knows how to turn database responses into objects and updated objects into database queries. The application interface (“Repositories”) provides an API for composing queries and creating/updating/deleting records. It looks very different depending on each specific ORM creator’s opinion.
Querying records
The query part of the interface is pretty common.
The query part of the interface is pretty common. Some ORMs let us find records by specific fields, like ...