In Zend Framework 1 I had several mappers which inherited a setDbTable and getDbTable from a parent Mapper class.
Now in ZF2 a face the problem that I need the service manager in a model and I do not have a clue as how to get it:
class Mapper
{
protected $tableGateway;
protected $module = 'application';
public function setTableGateway($table)
{
if (is_string($table)) {
$class = $this->module . '\Model\DbTable\\' . ucfirst($table);
$sm = $this->getServiceLocator(); <= Fatal error: Call to undefined method Mapper::getServiceLocator()
$tableGateway = (class_exists($class)) ? $sm->get($class) : $sm->get(new TableGateway($table));
} else {
$tableGateway = $table;
}
if (!$tableGateway instanceof Zend\Db\TableGateway\AbstractTableGateway) {
throw new \Exception('Invalid table data gateway provided');
}
$this->tableGateway = $tableGateway;
return $this;
}
// more code
The line:
$sm = $this->getServiceLocator();
gives a fatal error:
Call to undefined method Application\Model\Mapper\Doc::getServiceLocator()
How would I get the service manager in my model? Or am I not doing things the ZF2 way? I know how to get the service manager in my controller and pass the tableGateway to the mapper but that seems like a lot of duplication of code to me.