我将 Symfony 的控制台组件与 Zend_CodeGenerator 组件一起使用。例子很少,但我得到了它的工作 - http://framework.zend.com/manual/1.12/en/zend.codegenerator.html。当然,它不处理名称空间和use
语句。今天我想我试试Zend/Code/Generator。我在这里找到了一篇旧帖子 http://mwop.net/blog/261-Code-Generation-with-ZendCodeGenerator.html。
因此,我使用 Composer 安装了组件并更新了我的代码(见下文)。我遇到了未生成文档块的问题(请参阅新版本)。没有结果错误表明参数错误只是没有文档块。我快速查看了源代码、api 甚至一些单元测试。所以在我放弃这个并坚持使用 ZF1 CodeGenerator 之前,我想知道是否有任何使用 docblocks 的示例。
旧版
<?php
$class = new Zend_CodeGenerator_Php_Class();
$docblock = new Zend_CodeGenerator_Php_Docblock(array(
'shortDescription' => 'Index controller',
'tags' => array(
array(
'name' => 'category',
'description' => 'Controller',
),
array(
'name' => 'package',
'description' => 'Application\Controller',
),
),
));
$methods = array(
array(
'name' => 'indexAction',
'docblock' => new Zend_CodeGenerator_Php_Docblock(array(
'shortDescription' => 'Index action',
'tags' => array(
new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
'datatype' => 'void',
)),
),
)),
),
);
$class->setName("Admin_IndexController")
// Additional step needed to add namespace and use statement
->setExtendedClass('Action')
->setDocblock($docblock)
->setMethods($methods);
$file = new Zend_CodeGenerator_Php_File(array(
'classes' => array($class),
));
$code = $file->generate();
// Remove all that extra blank lines
$code = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $code);
if (file_put_contents('application/modules/admin/controllers/IndexController.php', $code)) {
$this->output->writeln(
'Controller generated ' . realpath('application/modules/admin/controllers/IndexController.php')
);
}
新版本
<?php
$classGenerator = new ClassGenerator();
$classGenerator->setName('Admin_IndexController')
->setExtendedClass('Action')
->setDocBlock(
new DocBlockGenerator(
'Index controller',
'',
array(
new Tag(
array(
'name' => 'category',
'description' => 'Controller'
)
),
new Tag(
array(
'name' => 'package',
'description' => 'Application\Controller'
)
)
)
)
)
->addMethods(
array(
new MethodGenerator(
'indexAction',
array(),
null,
null,
new DocBlockGenerator(
'Index action'
)
)
)
);
$fileGenerator = new FileGenerator();
$fileGenerator->setUse('Application\Controller\Action')
->setClass($classGenerator);
$code = $fileGenerator->generate();
// ...