Skip to content

Instantly share code, notes, and snippets.

@Ocramius
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ocramius/52fc7801d6dfc56b521b to your computer and use it in GitHub Desktop.
Save Ocramius/52fc7801d6dfc56b521b to your computer and use it in GitHub Desktop.

Assuming your application has an entity MyModule\Entity\Article, a DB table article and a DB connection service 'Zend\Db\Adapter\AdapterInterface', you will now be able to retrieve table gateways for each entity in namespace MyModule\Entity as following:

<?php

$articles = $serviceManager->get('MyModule\TableGateway\Article');
$comments = $serviceManager->get('MyModule\TableGateway\Comment');

// profit!
<?php
namespace MyModule;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Filter\Word\CamelCaseToUnderscore;
use Zend\Db\Resultset\HydratingResultSet;
use Zend\Stdlib\Hydrator\ClassMethods;
class AbstractTableGatewayFactory implements AbstractFactoryInterface
{
const DB_ADAPTER_NAME = 'Zend\\Db\\Adapter\\AdapterInterface';
const SUPPORTED_TABLE_GATEWAY_NAMESPACE = 'MyModule\\TableGateway\\';
const ENTITY_NAMESPACE = 'MyModule\\Entity\\';
/**
* {@inheritDoc}
*/
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return 0 === strpos($requestedName, self::SUPPORTED_TABLE_GATEWAY_NAMESPACE);
}
/**
* {@inheritDoc}
*/
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
// apply inflector logic here, if necessary
$gatewayName = str_replace(self::SUPPORTED_TABLE_GATEWAY_NAMESPACE, '', $requestedName);
$entityName = self::ENTITY_NAMESPACE . $gatewayName;
$prototype = new $entityName();
$tableName = (new CamelCaseToUnderscore())->filter($gatewayName);
/* @var $dbAdapter \Zend\Db\Adapter\Adapter */
$dbAdapter = $serviceLocator->get(self::DB_ADAPTER_NAME);
$resultSet = new HydratingResultSet(new ClassMethods(), new $entityName());
return new TableGateway($tableName, $dbAdapter, null, $resultSet);
}
}
<?php
return [
'service_manager' => [
'abstract_factories' => [
'MyModule\AbstractTableGatewayFactory',
],
],
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment