ChainableFormatter

Обсуждение документации. Переводы Cookbook и авторские рецепты.
Ответить
AlTiger
Сообщения: 199
Зарегистрирован: 2012.01.15, 18:37

ChainableFormatter

Сообщение AlTiger »

Когда CFormatter расширяют, добавляя свои методы, очень удобно делать последовательный вызов фильтров. Yii::app()->format()->plural(3,'яблоко','яблока','яблок')->text();

Задача: применить последовательный вызов методов к CFormatter'у

Для начала переопределим format в конфиге приложения

Код: Выделить всё

        'format' => array(
            'class' => 'ChainableFormatter',
        ),
 
И реализуем его

Код: Выделить всё

class ChainableFormatter extends CFormatter
{
    /**
     * @var string
     */
    protected $value = NULL;

    public function __call( $name, array $arguments )
    {
        if( NULL !== $this->value )
        {
            array_unshift( $arguments, $this->value );
            $this->value = parent::__call( $name, $arguments );

            return $this;
        }

        return parent::__call( $name, $arguments );
    }

    public function __toString()
    {
        if( NULL !== $this->value )
        {
            $tmp         = $this->value;
            $this->value = NULL;

            return (string)$tmp;
        }
    }

    public function chain( $string )
    {
        $this->value = $string;

        return $this;
    }

    static function formatPlural( $n, $form1, $form2, $form5 )
    {
        $n  = abs( $n ) % 100;
        $n1 = $n % 10;
        if( $n > 10 && $n < 20 )
        {
            return $form5;
        }
        if( $n1 > 1 && $n1 < 5 )
        {
            return $form2;
        }
        if( $n1 == 1 )
        {
            return $form1;
        }

        return $form5;
    }
}
 
Теперь в коде нам доступны следующие конструкции

Код: Выделить всё

Yii::app()->format->text('string<br>string');
Yii::app()->format->chain("string\string")->ntext()->text();
 
Ответить