LoginSignup
8
7

More than 5 years have passed since last update.

Phalcon で Plugin クラスを使う

Posted at

Plugin クラス

Plugin は EventManager などに attach() させて処理を埋め込む感じで使うらしい.

下記のものは例.実験した限りだと attach() した順番で呼ばれるので,アクションが実行される前,あるいはされた後のフィルタとして使える?(javax.servlet.FilterPlay2 の play.mvc.api.FilterRails のフィルタ のような)
サンプルからこう使うんだろうなぁという推測でやったような感じ.

<?php

namespace Timeline\Frontend;

use Phalcon\Loader;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
use Timeline\Frontend\Plugins\Header;

class Module implements ModuleDefinitionInterface
{
    public function registerAutoloaders()
    {
        $loader = new Loader();
        $loader->registerNamespaces(array(
            'Timeline\Frontend\Plugins' => __DIR__.'/plugins/',
        ));
        $loader->register();
    }

    public function registerServices($di)
        $di['dispatcher'] = function() use ($di) {
            $eventsManager = $di->getShared('eventsManager');
            $eventsManager->attach('dispatch', new Header($di));

            $dispatcher =  new Dispatcher();
            $dispatcher->setEventsManager($eventsManager);

            return $dispatcher;
        };
    }
}
<?php

namespace Timeline\Frontend\Plugins;

use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\User\Plugin;

class Header extends Plugin
{
    public function beforeDispatch(Event $event, Dispatcher $dispatcher)
    {
        $this->response->setHeader('X-Frame-Options', 'SAMEORIGIN');
        $this->response->setHeader('X-Content-Type-Options', 'nosniff');
    }

}

Header がちゃんと付与されているかの確認.

$ curl -s -I http://localhost/ | egrep "X-Frame-Options|X-Content-Type-Options"
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff

参考文献

Plugin と Component はどう違うの?

Plugin vs Component: what's the difference? - Discussion - Phalcon Framework

http://forum.phalconphp.com/discussion/383/plugin-vs-component-what-s-the-difference-

プラグインを使った例

チュートリアル 2: INVOについて説明します — Phalcon 1.3.1 documentation

http://docs.phalconphp.com/ja/latest/reference/tutorial-invo.html

プラグインとして実装する場合の例(ACL を使う)

PHP - Implementing an API ACL in Phalcon

http://www.rogerethomas.com/blog/php-implementing-an-api-acl-in-phalcon

紛らわしい記述だけど昔のドキュメントに "should not" と書かれていたらしい.今は気にしなくて良い様子.

WHY Plugins should not extend the class Phalcon\Mvc\User\Plugin? - Discussion - Phalcon Framework

http://forum.phalconphp.com/discussion/49/why-plugins-should-not-extend-the-class-phalcon-mvc-user-plugin-

上記の修正に対するコミットだと思う.

Re-adding 1.0.0 · 94eb834 · phalcon/docs

https://github.com/phalcon/docs/commit/94eb8342acfa895224754dc3f9d746a9fc36beb0#diff-13

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7