PHP勉強会@東京#58でPhakeの紹介をしました

第58回PHP勉強会@東京 - events.php.gr.jp

久々のPHP勉強会だったのでPhakeについて発表をしてきました。とても久々のPHP勉強会でしたが、懇親会で色々お話もできて楽しかったです。

訂正

Phake::mock()の第2引数以降がうんたら書いてますけど、第2引数以降がコンストラクタの引数になるのはパーシャルモックのときだけでした。


id:sotarokPHP 5.4の話のときにもいってたんですけど、「ゲッターセッター用意するの面倒だからAccessorってトレイトつくったよ!」「おれも!」みたいなことがあったりして、考えることはまったく同じですね。僕が作ってたときのソースさらしておきます。__call()をトレイトで実装しちゃうと、__call()が衝突しちゃうので一応メソッドわけてます。MagicCallMixerトレイトとか作ったけど消しちゃったらしい。

<?php
namespace Fivestar;

trait Accessor
{
    public function __call($method, $args)
    {
        return $this->callMagicAccessor($method, $args);
    }

    public function magicCallAccessor($method, $args)
    {   
        $processMethod = strtolower($method);
        if ('set' === ($verb = substr($processMethod, 0, 3)) 
            || 'get' === ($verb = substr($processMethod, 0, 3)) 
            || 'is' === ($verb = substr($processMethod, 0, 2)) 
        ) { 
            $camelName = lcfirst(substr($method, strlen($verb)));
            $underscoreName = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelName));

            $property = null;
            if (property_exists($this, $camelName)) {
                $property = $camelName;
            } elseif (property_exists($this, $underscoreName)) {
                $property = $underscoreName;
            }   

            if (null !== $property) {
                if ('set' === $verb) {
                    $this->{$property} = array_shift($args);

                    return;
                } elseif ('get' === $verb || 'is' === $verb) {
                    return $this->{$property};
                }   
            }   
        }   

        throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s', get_class($this), $method));
    } 
}

最後に、会場を提供していただいたVOYAGE GROUPさん、ありがとうございました。