How to read comments from a class, function, or method?

4

I have already seen some implementations in the framework Symfony and Laravel that allow to define through comments routes in controller methods, or Doctrine Models annotation definitions.

More or less like this:

class Usuariosontroller

{
    /**
     * @Route('GET', 'usuarios')
    */
    public function getIndex()
    {

    }

}

How do frameworks read this block of comments over methods?

    
asked by anonymous 17.08.2018 / 19:29

2 answers

7

Class

Using ReflectionClass to access the class, and thus get the comment value using method getDocComment :

$reflection = new ReflectionClass('Usuariosontroller');
echo $reflection->getDocComment();

Example Ideone .

Method

Using ReflectionClass to access the class, now use the getMethod to access the method you want to obtain the information by using the getDocComment :

$reflection = new ReflectionClass('Usuariosontroller'); 
echo $reflection->getMethod('getIndex')->getDocComment();

Example Ideone .

Function

Use ReflectionFunction to access the function, in sequence the getDocComment to access the comment:

$reflection = new ReflectionFunction('beber');
$reflection->getDocComment()    

Example Ideone .

Note:

There are a few ways to make a comment, however, the above methods worked only if you use the comment whose token is T_DOC_COMMENT , ie comments that obey the syntax: /** */ , then comments using the token T_COMMENT - syntax // or #, and /* */ - will be ignored.

    
17.08.2018 / 19:50
1

You can also use token_get_all php native .

index.php file

/**

    COMENTÁRIO

*/

function foo(){
    echo "foo";
}

Running ...

$array = token_get_all(file_get_contents("index.php"));

foreach($array as $arr){
    if(isset($arr[0]) && ($arr[0] == T_DOC_COMMENT || $arr[0] == T_COMMENT)){
        print_r($arr[1]);
    }
}

output:

  

/ ** COMMENT * /

    
17.08.2018 / 19:53