title: zf2: how to get service manager in mapper
body: <p>In Zend Framework 1 I had several mappers which inherited a setDbTable and getDbTable from a parent Mapper class.</p>
  
  <p>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:</p>
  
  <pre><code>    class Mapper
      {
          protected $tableGateway;
          protected $module = 'application';
  
          public function setTableGateway($table)
              {
                  if (is_string($table)) {
                      $class = $this-&gt;module . '\Model\DbTable\\' . ucfirst($table);
                      $sm = $this-&gt;getServiceLocator(); &lt;= Fatal error: Call to undefined method Mapper::getServiceLocator()
                      $tableGateway = (class_exists($class)) ? $sm-&gt;get($class) : $sm-&gt;get(new TableGateway($table));
                  } else {
                      $tableGateway = $table;
                  }
  
                  if (!$tableGateway instanceof Zend\Db\TableGateway\AbstractTableGateway) {
                      throw new \Exception('Invalid table data gateway provided');
                  }
                  $this-&gt;tableGateway = $tableGateway;
                  return $this;
              }
  
          // more code
  </code></pre>
  
  <p>The line:</p>
  
  <pre><code>$sm = $this-&gt;getServiceLocator();
  </code></pre>
  
  <p>gives a fatal error:</p>
  
  <pre><code>Call to undefined method Application\Model\Mapper\Doc::getServiceLocator()
  </code></pre>
  
  <p>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.</p>