标签: symfony

  • Symfony6生产环境Twig导致构建失败小记录

    最近把Symfony4升级到6,php版本也跟着升到8.2.5,体验了把新版本好处,但发现几个问题。

    默认的构建命令,symfony new my_project_directory --version="6.2.*",这是一个典型的API项目,也是我创建的类型。在API环境下,生产环境显然是不用任何模板功能的,但因为开发环境需要模板做展示,所以上线时候产生了一个BUG。

    当你加入composer.phar require --dev profiler为dev环境添加调试条的时候,你会发现一个问题,所有基于Profiler的依赖,例如Twig确实在composer.json的dev里。但是,在config/Bundles.php里却把因为Profiler依赖而加入的Twig模板引擎标记为全环境都需要Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],这里要改成Symfony\Bundle\TwigBundle\TwigBundle::class => ['dev' => true, 'test' => true]

    但这时候还没有完,config/packages/twig.yaml也需要删除,否则Symfony启动的时候检查到配置文件会自动调用,而导致报错。顺便把templates目录删除,这个是Twig默认加入的模板文件。

    最后,记得一点,composer install --no-dev --no-ansi --no-interaction --no-progress --classmap-authoritative --no-scripts --prefer-dist在你的composer安装命令中,千万不要--no-plugins,这会导致/vendor/autoload_runtime.php无法生成!

  • 利用Attribute特性和ValueResolverInterface为Symfony注入IP

    PHP8发布之后越发爱不释手,尤其Attribute比Annotation强大不少,Attribute可以对单个参数进行控制,这个功能很强大。演示一下控制器中通过Attribute描述字段来获得当前IP,其实一般解析器都是用来denormalize客户端POST过来的参数,但是为了用到Attribute,我用IP来举例。

    <?php
    namespace App\Resolver;
    use Attribute;
    
    #[Attribute(Attribute::TARGET_PARAMETER)]
    final class IP
    {
    }

    先设计一个Attribute申明,注意TARGET_PARAMETER标识作用在参数范围。

    <?php
    namespace App\Resolver;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
    use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
    
    class IPValueResolver implements ValueResolverInterface
    {
        public function resolve(Request $request, ArgumentMetadata $argument): iterable
        {
            $argumentType = $argument->getType();
            // 检查IP的Attribute
            $attributes = $argument->getAttributes(IP::class);
            if (count($attributes) == 0 || $argumentType !== 'string') {
                return [];
            }
            yield $request->getClientIp();
        }
    }

    其次,编写一个解析器,注意,Symfony 6.2开始提供ValueResolverInterface,之前版本用ArgumentValueResolverInterface

    public function resolver(#[IP] string $ip): Response

    最后,便是在任何控制器的方法中,只要使用了#[IP] string $ip就能方便的取得IP了。正确使用解析器,可以大大降低控制器中和Request对象耦合的重复代码,将预处理的流程都放在解析中!