PHPコードのアノテーション機能を自分で実装する

WBOY
リリース: 2016-08-08 09:24:20
オリジナル
2024 人が閲覧しました

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 チュートリアルに興味のある友人の参考になれば幸いです。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!