PHPコードの注釈特性を自ら実現する

2937 ワード

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を実現できる.