Skip to content

Instantly share code, notes, and snippets.

@kaiohken1982
Created September 21, 2012 13:16
Show Gist options
  • Save kaiohken1982/3761402 to your computer and use it in GitHub Desktop.
Save kaiohken1982/3761402 to your computer and use it in GitHub Desktop.
Zend Framework 2: get the ServiceManager in an Entity
<?php
namespace Album\Model;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class Album implements ServiceManagerAwareInterface
{
protected $serviceManager;
//...
public function getSongs()
{
return $this->getServiceManager()
->get('Album\Model\SongsTable')
->getSongsByAlbumId($this->getId());
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
public function getServiceManager()
{
return $this->serviceManager;
}
}
<?php
namespace Album\Model;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class AlbumsTable extends AbstractTableGateway
{
protected $serviceManager;
public function __construct(Adapter $adapter, ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
//$this->resultSetPrototype->setArrayObjectPrototype(new Album());
$this->resultSetPrototype->setArrayObjectPrototype(
$this->serviceManager->get('Album\Model\Album')
);
$this->initialize();
}
//...
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumsTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new AlbumsTable($dbAdapter, $sm);
return $table;
},
'Album\Model\Album' => function($sm) {
return new Model\Album();
},
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment