Skip to content

Instantly share code, notes, and snippets.

@bitkorn
Created June 2, 2019 05:18
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 bitkorn/b69dc36686afc043b026d055fc581014 to your computer and use it in GitHub Desktop.
Save bitkorn/b69dc36686afc043b026d055fc581014 to your computer and use it in GitHub Desktop.
This function tries to create a clean ZF3 controller factory
<?php
/**
* @param FolderTool $folderTool
* @return bool
*/
public function createType_zendWay(FolderTool $folderTool): bool
{
$filePath = $this->directory . '/' . $this->classname . '.php';
$file = new \Zend\Code\Generator\FileGenerator();
$file->setFilename($filePath);
$methodGenerator = new \Zend\Code\Generator\MethodGenerator();
$methodGenerator->setFlags([\Zend\Code\Generator\MethodGenerator::FLAG_PUBLIC]);
$methodGenerator->setName('__invoke');
/**
* use Interop\Container\ContainerInterface;
* ContainerInterface does not work ... it is always \ ContainerInterface
*/
$methodGenerator->setParameter(['name' => 'container', 'type' => ContainerInterface::class]);
$methodGenerator->setParameter((new \Zend\Code\Generator\ParameterGenerator('requestedName')));
/**
* null does not work ... it's always 'null'
*/
$methodGenerator->setParameter((new \Zend\Code\Generator\ParameterGenerator('options', 'array')));
$methodGenerator->setDocBlock(DocBlockGenerator::fromArray([
'shortDescription' => 'Create an object of type ' . $this->classnameMake . '()',
'longDescription' => null,
'tags' => [
new \Zend\Code\Generator\DocBlock\Tag\ParamTag('container', ['ContainerInterface']),
new \Zend\Code\Generator\DocBlock\Tag\ParamTag('requestedName', ['string']),
new \Zend\Code\Generator\DocBlock\Tag\ParamTag('options', ['null', 'array']),
new \Zend\Code\Generator\DocBlock\Tag\ReturnTag([$this->classnameMake]),
new \Zend\Code\Generator\DocBlock\Tag\ThrowsTag(['ServiceNotFoundException'], 'if unable to resolve the service'),
new \Zend\Code\Generator\DocBlock\Tag\ThrowsTag(['ServiceNotCreatedException'], 'if an exception is raised when creating a service'),
new \Zend\Code\Generator\DocBlock\Tag\ThrowsTag(['ContainerException'], 'if any other error occurs')
]
]));
$methodGenerator->setBody('$controller = new ' . $this->classnameMake . '();' . "\n" . 'return $controller;');
$classGenerator = new \Zend\Code\Generator\ClassGenerator();
$classGenerator->addMethodFromGenerator($methodGenerator);
$file->setBody($classGenerator->generate());
$file->write();
return $folderTool->chmodFile($filePath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment