Antipattern: The Model Is an Active Record

In simple applications, we don’t need a lot of custom logic in a model. It’s relatively straightforward to match the fields of a model object with the columns of a single table in a database. This is a type of object-relational mapping. All we need the object to do is know how to create, read, update and delete a row in the table — the basic CRUD operations.

Martin Fowler described a design pattern to support this mapping, called Active RecordMartin Fowler. Patterns of Enterprise Application Architecture. Addison Wesley Longman, Reading, MA, 2003.. Active Record is a data access pattern. We define a class corresponding to a table or view in our database. We can call a class method find() that returns an object instance of the class corresponding to an individual row in that table or view. We can also use the class constructor to create a new row. Calling save() on this object either inserts a new row or updates the existing row.

<?php
$bugsTable = Doctrine_Core::getTable('Bugs');
$bugsTable->find(1234);

$bug = new Bugs();
$bug->summary = "Crashes when I save";
$bug->save();
?>

Ruby on Rails popularized Active Record for web development frameworks in 2004, and now most web application frameworks use this pattern as their de facto data access object (DAO). There’s nothing wrong with using Active Record; it’s a fine pattern that provides a simple interface to individual rows in a single table. The antipattern is the convention that all model classes in an MVC application inherit from the base Active Record class. This is an example of the Golden Hammer antipattern: if the only tool one has is a hammer, they’ll treat everything as if it were a nail.

Get hands-on with 1200+ tech skills courses.