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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看