自行实现PHP代码注解特性

WBOY
Freigeben: 2016-08-08 09:24:20
Original
2028 Leute haben es durchsucht

PHP 注解

到目前为止,PHP的反射特性中是不支持注解Annotation的,但是可以支持基本的文档注释内容的获取 ReflectionMethod::getDocComment() - 从5.1.0开始 。PHP的反射其实已经挺强大的了,只要再进一步,解析文档注释中的相关注解内容即可。

AppServer.io 提供了一个lang库,实现了对注解的支持。其中还运用了PHP的Tokenizer特性来解析注解代码,具体原理不详述,有兴趣自行阅读代码。
https://github.com/appserver-io/lang

其关于注解的说明见:http://appserver.io/get-started/documentation/annotations.html

在此摘录其演示代码如下:

<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>
Nach dem Login kopieren

通过这种特性,可以实现注解的方式指定方法的url路由模式 /index/index

以上就介绍了自行实现PHP代码注解特性,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!