Germania KG * RequestHandler for Twig
Installation
Setup
The constructor accepts a Twig Environment and PSR-17 ResponseFactory. This example uses Tobias Nyholm's nyholm/psr7 package: composer require nyholm/psr7
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);
Usage
Have a ServerRequest at hand and configure it with a template attribute and a context attribute.
- The template attribute must be a string as required by Twig.
- The context attribute must be an array as required by Twig; Instances of ArrayObject will be converted.
N.B. Invalid variable types will lead to a RuntimeException at runtime on request handling, not during configuration!
$request = $psr17Factory->createServerRequest('GET', 'http://tnyholm.se');
$request = $request
->withAttribute('template', 'website.twig')
->withAttribute('context', [
'title' => 'The Website title',
'company' => 'ACME corp.'
]);
Now, the above RequestHandler can be used as normal:
echo $response->getBody()->__toString();
// s.th. like
// "
Configuration
You can change these default settings:
$request_handler->setResponseFactory($another);
You can change these default settings
->setContextAttributeName("context")
->setResponseContentType("text/html")
->setResponseStatusCode(200);
... and the core components:
->setResponseFactory($another);
Issues
Development
Grab and go using one of these:
$ gh repo clone GermaniaKG/TwigRequestHandler
Unit tests
Either copy phpunit.xml.dist to phpunit.xml and adapt to your needs, or leave as is. Run PhpUnit test or composer scripts like this:
# or
$ vendor/bin/phpunit