I was looking for a way to automatically generate some documentation, and because all the required information was already in the DocComment blocks. I downloaded the great documentation generator DocBlox (which is a PHP application by itself) and looked in it’s source code. Soon I found DocBlox’s Reflection classes which are able to parse a DocComment block. So I wanted to use these classes! Here is how you can do it:
- Download the latest DocBlox zip file
- Unzip the archive
- Create the directory
/vendor/docblox/src/DocBloxin your Symfony2 project - From the archive:
- copy
/src/DocBlox/Reflectionand it’s contents to the directory you have just created - copy
/src/markdown.phpand the directory/src/markdownand it’s contents to/src/vendor/docblox/src - Copy
/LICENSEto/vendor/docblox
- copy
Now your directory structure should look like:
/vendor
/docblox
/src
/DocBlox
/Reflection/*
/markdown/*
/markdown.php
/LICENSE
The license requires you to copy it with the code, even if you use part of it.
Now open /app/autoload.php and add the “DocBlox_” prefix to the autoloader:
$loader->registerPrefixes(array(
'Twig_Extensions_' => __DIR__.'/../vendor/twig-extensions/lib',
'Twig_' => __DIR__.'/../vendor/twig/lib',
// ...
'DocBlox_' => __DIR__.'/../vendor/docblox/src',
));
Also add this line to /app/autoload.php:
require_once __DIR__.'/../vendor/docblox/src/markdown.php';
This will enable you to use Markdown formatting in your DocBlocks.
The DocBlox reflection classes are now available in your project. I tested my configuration by creating the following action, which displays the type and description of it’s own return value:
/**
* Displays it's own "return" tag
*
* The "docBlox" action uses the DocBlox "DocBlock" reflection class
*
* @return Symfony\Component\HttpFoundation\Response The response
*/
public function docBloxAction()
{
$reflectionMethod = new \ReflectionMethod($this, 'docBloxAction');
$docBlock = new \DocBlox_Reflection_DocBlock($reflectionMethod);
$returns = $docBlock->getTagsByName('return');
if (!empty($returns)) {
$return = reset($returns); // get the first "return" tag
/* @var $return DocBlox_Reflection_DocBlock_Tag_Return */
$type = $return->getType();
$description = $return->getDescription();
return new Response(sprintf('This method returns a %s which is %s', $type, lcfirst($description)));
}
return new Response('No return parameter was defined');
}
As you can see, there is a limitation to the API of DocBlox: there is no getTag() method, only a getTags() and a getTagsByName() method, that both return an array. So you will have to reduce this to one tag yourself (for example by calling reset() on the array).
When this action is called, it renders the following text:
This method returns a Symfony\Component\HttpFoundation\Response which is the response
# October 25, 2011 at 17:28
Reply
# October 25, 2011 at 19:30
Reply
# October 25, 2011 at 22:15
Reply
# March 3, 2012 at 03:43
Reply
# March 3, 2012 at 09:34
Reply