Skip to content

Instantly share code, notes, and snippets.

@Ocramius
Last active October 21, 2017 12:55
Show Gist options
  • Save Ocramius/6542111 to your computer and use it in GitHub Desktop.
Save Ocramius/6542111 to your computer and use it in GitHub Desktop.
ZF2 Abstract controller factory to handle numerous doctrine entities at once
<?php
return [
'router' => [
'routes' => [
'restful' => [
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => [
'route' => '/my-stuff/:controller[/:id]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-z0-9]*',
],
],
],
],
],
// any un-known or not manually mapped controllers will hit this abstract factory
'controllers' => [
'abstract_factories' => [
'MyModule\AbstractEntityControllerFactory',
],
],
// this is a map of controller names to entity names. That allows us to workaround
// any issue with camelCase or Some\Namespace problem that are hard to handle via normalization
'entity_controllers' => [
'address' => 'MyModule\Entity\Address',
'person' => 'MyModule\Entity\Person\BusinessContact',
],
];
<?php
namespace MyModule;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\AbstractPluginManager;
class AbstractEntityControllerFactory implements AbstractFactoryInterface
{
/**
* {@inheritDoc}
*/
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
if (! $serviceLocator instanceof AbstractPluginManager) {
throw new \BadMethodCallException('This abstract factory is meant to be used only with a plugin manager');
}
$parentLocator = $serviceLocator->getServiceLocator();
$config = $parentLocator->get('config');
return isset($config['entity_controllers'][$requestedName]);
}
/**
* {@inheritDoc}
*/
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
if (! $this->canCreateServiceWithName($serviceLocator, $name, $requestedName)) {
throw new \BadMethodCallException('This abstract factory can\'t create service "' . $requestedName . '"');
}
$parentLocator = $serviceLocator->getServiceLocator();
$config = $parentLocator->get('config');
$entityName = $config['entity_controllers'][$requestedName];
return new BaseEntityController($entityName);
}
}
@7Style
Copy link

7Style commented Apr 23, 2014

Hi, Kann man das nicht dynamisieren? also die $contoller und $action dynamisch holen ?

@Ocramius
Copy link
Author

@7Style sure, if you want a MASSIVE security issue. The config was added exactly to prevent that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment