Skip to content

Instantly share code, notes, and snippets.

@sanhuang
Last active October 5, 2016 15:31
Show Gist options
  • Save sanhuang/8c4bcab6048d00defa9d16e0e715d8a8 to your computer and use it in GitHub Desktop.
Save sanhuang/8c4bcab6048d00defa9d16e0e715d8a8 to your computer and use it in GitHub Desktop.
紀錄如何利用Phalcon\Annotations直接在Action()內處理當下Class的parser註釋

Annotations parser Action() comment of Controller

某一個Contrller範本

/**
 * @module content
 *
 * @buildresource("hello", "world", 1, 2, 3, false, true)
 *
 * @checkPrivileges(
    resource:Page,
    route="/content/page/*",
    permission={
        allow:[role1, role2]
    }
   )
 * */
class FaqController extends ControllerBase
{
    public function initialize() {
        parent::initialize();
    }


    /**
     *
     * */
    public function indexAction()
    {
        $reflector=$this->annotations->get( "House\Content\Controllers\FaqController" );
        $annotations = $reflector->getClassAnnotations();

        // Traverse the annotations
        foreach ($annotations as $annotation) {
            // Print the annotation name
            echo $annotation->getName()."<BR/>";

            // Print the number of arguments
            echo $annotation->numberArguments()."<BR/>";

            // Print the getArguments
            var_dump($annotation->getArguments());
        }

        $actes=$reflector->getMethodsAnnotations();

        foreach ($actes as $annotation) {

            if( $annotation->has("checkPrivileges") ){
                foreach ($annotation as $anno) {
                    var_dump($anno->getName());
                    var_dump($anno->getArguments());
                }
            }
            // Print the annotation name
            // echo $annotation->getName()."<BR/>";

            // Print the number of arguments
            // echo $annotation->numberArguments()."<BR/>";

            // Print the arguments
        }
        die();
    }


}

其中,在*public function indexAction()*內可以透過DI直接取得Annotations

$reflector=$this->annotations->get( "House\Content\Controllers\FaqController" );

注意!透過這樣方式得到的*$reflector*是一整個Annotations物件集合並非單一Annotation,故後續應該再用迴圈取得單一Annotation進行處理

$annotations = $reflector->getClassAnnotations();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment