danilovl/render-service-twig-extension-bundle

Symfony twig 扩展包提供渲染服务方法

v4.0.2 2024-04-06 12:30 UTC

README

phpunit downloads latest Stable Version license

RenderServiceTwigExtensionBundle

关于

Symfony twig 扩展包提供了一种简单的方法,通过服务方法或对象创建函数或过滤器。

此扩展的主要任务是用现有的 twig 方法 render(controller()) 进行替换。

现有方法的主要缺点是它执行了一个子请求,这增加了总的查询执行时间。

性能比较指标

在这个例子中,使用了相同的页面,唯一的区别是标准 render(controller()) 方法使用的次数与新的运行时 twig 函数相比。

左侧可以看到标准 twig 函数的使用,而右侧使用的是运行时 twig 函数。

渲染三次。

Alt text

渲染十次。

Alt text

要求

  • PHP 8.3 或更高版本
  • Symfony 7.0 或更高版本

1. 安装

使用 Composer 安装 danilovl/render-service-twig-extension-bundle

composer require danilovl/render-service-twig-extension-bundle

如果未自动添加,请将 RenderServiceTwigExtensionBundle 添加到您的应用程序包中

<?php
// config/bundles.php

return [
    // ...
    Danilovl\RenderServiceTwigExtensionBundle\RenderServiceTwigExtensionBundle::class => ['all' => true]
];

2. 配置

您可以设置所有扩展的全局参数。

danilovl_render_service:
  prefix: null
  to_snake_case: true

  filter_options:
    needs_environment: false
    needs_context: false
    is_variadic: false
    is_safe: []
    is_safe_callback: []
    pre_escape: null
    preserves_safety: []
    node_class: FunctionExpression::class
    deprecated: false
    alternative: null

  function_options:
    needs_environment: false
    needs_context: false
    is_variadic: false
    is_safe: []
    is_safe_callback: []
    node_class: FunctionExpression::class
    deprecated: false
    alternative: null

3. 使用

存在两个属性 AsTwigFilterAsTwigFunction,可以与类或方法一起使用。

当您使用属性与一个类一起使用时,这意味着所有公共类方法都自动转换为过滤器或函数。

例如,它创建两个函数:math_summath_min

如果设置了全局前缀如 app_,则将创建:app_math_sumapp_math_min

全局参数 to_snake_case 设置为 true,这意味着方法名称被转换为 snake_case。您可以禁用此功能。

<?php declare(strict_types=1);

namespace App\Application\Controller;

use Danilovl\RenderServiceTwigExtensionBundle\Attribute\AsTwigFunction;

#[AsTwigFunction('math_')]
class CountService
{
    public function sum(int $one, int $two): int
    {
        return $one + $two;
    }

    public function min(int $one, int $two): int
    {
        return $one - $two;
    }

    public function multiplicationOperation(int $one, int $two): int
    {
        return $one * $two;
    }
}
{{ app_math_sum(2,3) }}
{{ app_math_min(2,3) }}
{{ app_math_multiplication_operation(2,3) }}

您可以使用属性分别与特定方法一起使用。

<?php declare(strict_types=1);

namespace App\Application\Controller;

use Danilovl\RenderServiceTwigExtensionBundle\Attribute\{
    AsTwigFilter,
    AsTwigFunction
};

class RenderServiceController
{
    #[AsTwigFunction('function_sum')]
    public function twigFunctionSum(int $one, int $two): int
    {
        return $one + $two;
    }

    #[AsTwigFilter('filter_upper')]
    public function twigFilterUpper(string $text): string
    {
        return strtoupper($text);
    }
}
{{ 'text' | app_filter_upper }}
{{ app_function_sum(2,3) }}

4. 命令

显示由属性创建的 twig 扩展列表。

php bin/console danilovl:render-service:list

许可证

RenderServiceTwigExtensionBundle 是开源软件,许可协议为 MIT 许可证