首頁  >  文章  >  後端開發  >  自行實現PHP程式碼註解特性

自行實現PHP程式碼註解特性

WBOY
WBOY原創
2016-08-08 09:24:202024瀏覽

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>

透過此特性,可以實現註解的方式指定方法的url路由模式/index/index

以上就介紹了自行實現PHP程式碼註解特性,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn