3 mars 2011

Implement your own phpdoc annotations

The goal is to be able to implement our own phpdoc annotations for custom use.

Access the doc block of a method


...
  $method = new ReflectionMethod('MyClass', 'myMethod');
  $doc = $method->getDocComment();
  ...

A note from the php.net documentation about getDocComment():

In order to retrieve a comment with this method, the comment must be imediately before the class, function or method, start with /** and end with */

Does the method have the annotation?


...
  if (preg_match('/@my_annotation/, $doc) {

    // Do something interesting with $method

  }
  ...

Putting it all together


A function that dumps the public methods of a class unless they are marked with the @ignore annotation:

function listMethods($class_name) {

    foreach(get_class_methods($class_name) as $method_name) {

      $method = new \ReflectionMethod($class_name, $method_name);
      $doc = $method->getDocComment();

      if (! preg_match('/@ignore/', $doc)) {
        echo "$class_name.$method_name";
      }      
    }

  }

Aucun commentaire:

Enregistrer un commentaire