1.0.1 2015-12-20 00:19 UTC


The active record pattern is one where an object in the application maps to a single row in the database. This object exposes CRUD (create, read, update, and delete) methods for the related row.


`composer require digitalus/zend-active-record`

This Implementation

All of the AR (active record) models extend the ZendActiveRecord\Model base class which handles the underlying functionality. The implementation is simplistic and light weight by design, to avoid any interference between the AR implementation and individual model logic. The only dependency is a db adapter to handle db interaction.

Creating a Model

I'll model the fictitious fish table for an example. The model will have public properties for each of the fields in the fish table.

namespace Application\Model; // depending on the module

use ZendActiveRecord\Model;

class Fish extends Model { protected $tableName = 'fish';

public $id;
public $name;
public $taste;


Inserting a record

You insert a record into the database by creating an instance of the Fish model, then saving it.

$tuna = new Fish;
$tuna->name = 'bluefin tuna';
$tuna->taste = 'delicious';

Note When you call save the AR checks to see if the id is set, and since its not it inserts a record.

Finding Records

If you already know the id of the row you are looking for find() is the simplest way to fetch the row instance.

$fishModel = new Fish($dbAdapter);
$tunaId = 999;
$tuna = $fishModel->find($tunaId);


There are two methods to fetch data:

  • fetchRow($where)
  • fetchAll($where)

Both of these methods accept where conditions which can be null (return all), a Select object, or an array. The Select object gives you the most control.

$fishModel = new Fish($dbAdapter);

// fetch all fish
$allFish = $fishModel->fetchAll();

// find delicious fish
// with an array of filters
$filters = array('taste' => 'delicious');
$deliciousFish = $fishModel->fetchAll($filters);

// find them with the Zend Select object
$select = $fishModel->select();
$select->where('taste = "delicious"');
$deliciousFish = $fishModel->fetchAll($select);

Full documentation for the Zend Select object is available at:

Updating a Record

The functions above return instances (or a single instance) of the Fish object. This object is editable.

$tunaId = 999;
$tuna = $fishModel->find($tunaId);
$tuna->taste = 'best thing in the world';

Deleting a Record

You can delete any active record object, which will delete the underlying row in the database.

$tunaId = 999;
$tuna = $fishModel->find($tunaId);

If you have the id instead of an active record object you can pass the delete method the id of the row to remove.

$tunaId = 999;