Just create a class in your library or wherever you store common code, perhaps something like:
//library/My/Model/Mapper/Abstract.php
<?php
abstract class My_Model_Mapper_Abstract
{
/**
* Instance of Zend_Db_Table_Abstract
*
* @var Zend_Db_Table_Abstract $tableGateway
*/
protected $tableGateway = null;
/**
* sets up the identity map
*/
protected $map = array();
/**
* Will accept a DbTable model passed or will instantiate
* a Zend_Db_Table_Abstract object from table name.
*
* @param Zend_Db_Table_Abstract $tableGateway
*/
public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
if (is_null($tableGateway)) {
$this->tableGateway = new Zend_Db_Table($this->tableName);
} else {
$this->tableGateway = $tableGateway;
}
}
/**
* Get the default database table adapter.
*
* @return Zend_Db_Table_Abstract
*/
protected function getGateway()
{
return $this->tableGateway;
}
//truncated for space
public function findById($id)
{
if ($this->getMap($id)) {
return $this->getMap($id);
}
$select = $this->getGateway()->select();
$select->where('id = ?', $id);
$row = $this->getGateway()->fetchRow($select);
$entity = $this->createEntity($row);
$this->setMap($row->id, $entity);
return $entity;
}
//truncated for space
/**
* Abstract method to be implemented by concrete mappers.
*/
abstract protected function createEntity($row);
}
Then a concrete implementation might resemble:
//application/modules/users/model/mappers/User.php
<?php
class Users_Model_Mapper_User extends My_Model_Mapper_Abstract
{
protected $tableName = 'users';
public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
if (is_null($tableGateway)) {
//TODO: inject this resource
$tableGateway = new Application_Model_DbTable_User();
} else {
$tableGateway = $tableGateway;
}
parent::__construct($tableGateway);
}
protected function createEntity($row)
{
$data = array(
'id' => $row->id,
'username' => $row->username,
'password' => $row->password
);
$user = new Users_Model_User($data);
return $user;
}
private function hashPassword($password)
{
return Password::createPasswordHash($password);
}
public function saveUser(My_Model_Entity_Abstract $user)
{
if (!is_null($user->id)) {
$select = $this->getGateway()->select();
$select->where('id = ?', $user->id);
$row = $this->getGateway()->fetchRow($select);
} else {
$row = $this->getGateway()->createRow();
$row->password = $this->hashPassword($user->password);
}
$row->username = $user->username;
$row->save();
return $row;
}
}
These are created to utilize the DbTable Models commonly used in ZF1 and are still works in progress.
ZF2 models may be somewhat different as ZF2 implements and extends much more of the PHP SPL library so some modification will likely be useful.
Good Luck!