germania-kg/twig-requesthandler

PSR-15 请求处理器,用于渲染 Twig 模板

1.0.5 2021-02-11 06:52 UTC

This package is auto-updated.

Last update: 2024-09-11 14:33:16 UTC


README

Germania KG · Twig 请求处理器

Packagist PHP version Build Status Scrutinizer Code Quality Code Coverage Build Status

安装

$ composer require germania-kg/twig-requesthandler

设置

构造函数接受一个 Twig 环境PSR-17 响应工厂。此示例使用 Tobias Nyholm 的 nyholm/psr7 包: composer require nyholm/psr7

<?php

use Germania\TwigRequestHandler\TwigRequestHandler;  
use Twig\Environment as Twig;
use Nyholm\Psr7\Factory\Psr17Factory;

// Dependencies
$twig = new Twig( ... );
$psr17Factory = new Psr17Factory;

// Instantiation
$request_handler = new TwigRequestHandler($twig, $psr17Factory);

使用方法

ServerRequest,并配置其 template 属性和 context 属性。

  • template 属性必须是符合 Twig 要求的 字符串
  • context 属性必须是符合 Twig 要求的 数组ArrayObject 实例将被转换。

注意:无效的变量类型将导致在请求处理时抛出 RuntimeException,而不是在配置期间!

<?php
$request = $psr17Factory->createServerRequest('GET', 'http://tnyholm.se');

$request = $request
  ->withAttribute('template', 'website.twig')
  ->withAttribute('context', [
    'title' => 'The Website title',
    'company' => 'ACME corp.'
  ]);

现在,上述请求处理器可以像平常一样使用

$response = $request_handler->handle($request);

echo $response->getBody()->__toString();
// s.th. like 
// "<title>The Website title · ACME corp.</title>"

配置

您可以更改这些默认设置

$request_handler->setTwig($twig);
$request_handler->setResponseFactory($another);

您可以更改这些默认设置

$request_handler->setTemplateAttributeName("template")
						    ->setContextAttributeName("context")
                ->setResponseContentType("text/html") 
                ->setResponseStatusCode(200);

…以及核心组件

$request_handler->setTwig($twig)
                ->setResponseFactory($another);

问题

查看 完整问题列表。

开发

使用以下任一方法获取和运行

$ git clone git@github.com:GermaniaKG/TwigRequestHandler.git
$ gh repo clone GermaniaKG/TwigRequestHandler

单元测试

要么将 phpunit.xml.dist 复制到 phpunit.xml 并根据您的需要进行调整,要么保持不变。运行 PhpUnit 测试或 composer 脚本,如下所示

$ composer test
# or
$ vendor/bin/phpunit