Skip to content

Instantly share code, notes, and snippets.

@rsky
Last active December 14, 2015 10:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsky/5069716 to your computer and use it in GitHub Desktop.
Save rsky/5069716 to your computer and use it in GitHub Desktop.
ミックスインでAOPもどき(オレオレ改造PHPを使用)。 AOPサポートを追加すればInterceptor::invoke()の定義が不要になる。
実行例
/opt/php/exam/qiq/bin/php main.php
(before)
Hello!
(after)
<?php
trait Interceptor
{
public function before()
{
echo "(before)\n";
}
public function after()
{
echo "(after)\n";
}
public function invoke()
{
$this->before();
parent::invoke();
$this->after();
}
}
<?php
set_include_path(__DIR__);
spl_autoload_register();
function getInterceptor($class)
{
return 'Interceptor';
}
function getObject($class)
{
$interceptor = getInterceptor($class);
if ($interceptor) {
return new $class use $interceptor;
}
return new $class;
}
getObject('Subject')->invoke();
<?php
class Subject
{
public function invoke()
{
echo "Hello!\n";
}
}
@koriym
Copy link

koriym commented Mar 2, 2013

いいですね、mixinとの融合がいいです!
(名前は trait Weaver よりtrait Interceptor や trait MethodInterceptor の方がいいかもしれませんね。織り込む方ではなくて織り込まれる側なので。どうでしょうか)

@rsky
Copy link
Author

rsky commented Mar 2, 2013

確かに。直しました!

@koriym
Copy link

koriym commented Mar 2, 2013

new $class use $interceptor;

これがいいですね!インターセプターを使って(=use =織り込んで) $classが生まれてる感じがします。

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