Home  >  Article  >  Backend Development  >  Implement PHP code annotation features yourself

Implement PHP code annotation features yourself

WBOY
WBOYOriginal
2016-08-08 09:24:202023browse

PHP Annotation

So far, PHP’s reflection feature does not support annotation Annotation, but it can support the acquisition of basic document comment content ReflectionMethod::getDocComment() - starting from 5.1.0. PHP's reflection is actually quite powerful. You just need to go one step further and parse the relevant comments in the documentation comments.

AppServer.io provides a lang library to support annotations. The Tokenizer feature of PHP is also used to parse the annotation code. The specific principle is not detailed. If you are interested, you can read the code by yourself.
https://github.com/appserver-io/lang

For its description of annotations, see: http://appserver.io/get-started/documentation/annotations.html

The demo code is excerpted here as follows:

<code><?php

namespace Namespace\Module;

use AppserverIo\Appserver\Lang\Reflection\ReflectionClass;
use AppserverIo\Appserver\Lang\Reflection\ReflectionAnnotation;

class Route extends ReflectionAnnotation
{

  /**
   * Returns the value of the name attribute.
   *
   * @return string The annotations name attribute
   */
  public function getPattern()
  {
    return $this->values['pattern'];
  }
}

class IndexController
{

  /**
   * Default action implementation.
   * 
   * @return void
   * @Route(pattern="/index/index")
   */
  public function indexAction()
  {
    // do something here
  }
}

// create a reflection class to load the methods annotation 
$reflectionClass = new ReflectionClass('IndexController');
$reflectionMethod = $reflectionClass->getMethod('indexAction');
$reflectionAnnotation = $reflectionMethod->getAnnotation('Route');
$pattern = $reflectionAnnotation->newInstance()->getPattern();</code>

Through this feature, you can specify the url routing mode/index/index of the method in the form of annotations

The above has introduced the self-implementation of PHP code annotation features, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php string function (1)Next article:php string function (1)