From the course: PHP: Design Patterns

Introducing the active record pattern - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Introducing the active record pattern

- While there are a variety of different database access patterns, this is generally the simplest, so we'll cover it first. So, let's talk about the problem we're solving. Many of our applications boil down to very simple operations with respect to a database. We write records, we retrieve them, we update them and we delete them. It's traditional crud. On the other side of things, those database records are usually loaded in objects. In some regards, you probably spend more time in code doing that more than anything else. We can simplify all this using the active-record pattern. The point of active-record is that it maps database rows into individual objects. Then than object is responsible for knowing how to create, retrieve, update, and delete the underlying database entry. The vast majority of the time the database fields translate to object properties and vice versa without any manipulation This is usually powered by an ORM or Object Relational Mapper. This is primarily useful to eliminate or prevent duplication in our code. By having a simple mapping between our database columns and object properties, we can treat every object the same. More importantly, we can have a single set of business logic that handles all the database interactions. If we need to do any sort of data validation, permissions, checking, or even events triggered based on the database. We can do that here. But like any pattern, it has some drawbacks. First, our objects are tightly coupled to the database. The individual object properties map one-to-one with our database schema. So, if the database or the object needs a change, the other one has to also. Second, since this pattern is so closely tied to the database it's hard to test the code without using an actual database. When we're talking about unit testing database acts slows down the process and sometimes makes it impossible. The second point can be mitigated by using dependency injection or mocking, but there's still an issue. If you're interested in mocking or mock objects check out Chapter 5 for more details. But this would make a lot more sense with a concrete example, so let's dive into one.

Contents