sergiosgc/negotiated-output

基于内容协商的模板路由器

dev-master 2023-04-11 15:26 UTC

This package is auto-updated.

Last update: 2024-09-11 18:51:37 UTC


README

基于内容协商的模板路由器

目标

一个典型的PHP应用程序在两个阶段处理请求:

  1. 执行请求操作
  2. 生成输出

在RESTful应用程序中,输出取决于对方是谁。如果是人类,则输出是HTML;如果不是,则是某种可编程消耗的数据格式(通常是JSON或XML)。

此包使用Accepts HTTP头决定输出类型,并调用所需的模板脚本以生成正确类型的输出。它对模板引擎解决方案不可知。它只是将输出逻辑路由到文件系统中适当的脚本。

使用场景

<?php
require_once('vendor/autoload.php');
// [Placeholder for application code handling the request]
(new \sergiosgc\output\Negotiated('templates', array('application/json; charset=UTF-8', 'text/html; charset=UTF-8')))->output();

最后一行脚本将包含来自 <document_root>/templates/text-html<document_root>/templates/application-json 的文件。决策是通过HTTP Accept头进行的。

实际包含的文件是从请求URL映射的。URL直接映射到文件系统。对于text/html响应,URL /foo/bar 将包含 <document_root>/templates/text-html/foo/bar/index.php。如果没有找到精确匹配,则会向上遍历文件系统,直到找到模板文件:例如 <document_root>/templates/text-html/foo/index.php,然后 <document_root>/templates/text-html/index.php

如果使用 sergiosgc/rest-router,则要包含的模板文件不是 index.php,而是 <http_verb>.php(例如,get.phppost.php)。

安装

通过Composer安装。composer.json

# composer.json
{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/sergiosgc/composer-negotiated-output.git"
        }
    ],
    "require": {
        "sergiosgc/negotiated-output": "dev-master"
    }
}

与sergiosgc/rest-router一起使用

如果使用sergiosgc/rest-router,则通配符脚本应如下所示:

<?php
require_once('vendor/autoload.php');
// [Placeholder for application initialization code]
(new \sergiosgc\router\Rest('rest'))->route();
(new \sergiosgc\output\Negotiated('templates', array('application/json; charset=UTF-8', 'text/html; charset=UTF-8')))->output();