duanhemou9834 2019-02-27 18:14
浏览 107

如果函数有另一个参数,则使用上下文变量作为参数在Twig中调用PHP函数

In PHP I have:

protected function registerTwigFunctions()
{
    return [
        'count_VKcomments' => 'countVKCommentsFunction'
    ];
}

public function countVKCommentsFunction($context, $pdo) {
    $url = $context['url'];
    $sql = "SELECT id, COUNT(*) FROM level_1 WHERE url = ?";
    $count = $pdo->prepare($sql)->execute([$url])->fetchColumn();
    return $count;
}

In Twig I have:

{% set url = global.request.uri %}
{{ count_VKcomments({ 'url': url }) }

But it only works if I remove the $pdo argument from countVKCommentsFunction, otherwise some temporary file complains about too few arguments being passed from Twig. But I need to include that $pdo argument just to avoid duplicating connection to the database, which is already defined as $pdo in another function. At the same time, I don't understand how to properly call countVKCommentsFunction provided that it needs $pdo as an argument.

  • 写回答

2条回答 默认 最新

  • dqsk4643 2019-02-27 18:37
    关注

    From perspective of Twig your function should only accept/care about what template practically needs to pass to it.

    From perspective of PHP implementation your function needs access to state of your application (your database connection in this case).

    The solution here is to decouple the two tasks:

    1. Make and instantiate object that has access to the necessary state.
    2. Use the object's method as callback for Twig function.

    That way template data comes through arguments and state data comes through implementation.

    评论

报告相同问题?