我将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我安装了组件并开始更新我的代码(见下文)。我遇到了没有生成doc块的问题(参见新版本)。没有结果错误表明参数错误,只是没有docblocks。我很快回顾了源代码,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();
// ...