LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

phalcon voltにオリジナルやphpのFuctionを追加する方法

phalconのVoltを拡張

ここにあるのですが、
ズバリな回答じゃないので。。

config/services.php

config/service.php
$compiler->addFunction(
    "widget",
    function ($resolvedArgs, $exprArgs) {
        return "MyLibrary\\Widgets::get(" . $resolvedArgs . ")";
    }
);

こんな記述があるんですが、
たぶん、Viewの拡張をするところで、voltの動作を定義しているところがあります。そこに追加する感じになると思います。

:helmet_with_cross:注意点は、実行したいFunction名を文字列で返すというところ。ここ大事

$di->setShared('view', function() {
}

シンプルにphpのdate_format関数を追加する場合

$volt->getCompiler()->addFunction('date_format', 'date_format');

以下、なんかちょっと処理を入れる場合、postされたデータをbase64_decodeを追加する方法

$volt->getCompiler()->addFunction('base64_decode', function($args) {
          $str = str_replace(' ', '+', $args);
          return "base64_decode({$str})";
});

引数がたくさんある場合

$volt->getCompiler()->addFunction('mb_strimwidth', function($args) {
          return "mb_strimwidth({$args})";
});

ここがちょっとおもしろいところで、addFunction のところの第2引数にfunction($args)としてますが、ここは複数引数指定されたらそれらの文字列が渡ってくるのです。

使うときはこんな感じだけど

{{ mb_strimwidth(str,0,10,"...") }}

上記でいう
$args
には、

str,0,10,"..."

という文字列が入ってくるので、そのままセットすればよいです。

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
What you can do with signing up
0