自行實現PHP代碼注解特性


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

在此摘錄其演示代碼如下:

<?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();

通過這種特性,可以實現注解的方式指定方法的url路由模式 /index/index


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM