我想知道最好的编码实践,它允许客户端为他所做的请求定义响应格式,也可以包括过滤器,条件,排序等......
我为答案制作了一个小模板,我不知道这是否是最佳做法,但它有效(建议是受欢迎的)。我在()之后没有编写中间件;
PS:构建请求代码后,格式的选择将是动态的。
现在关于申请。我想我会在()之前对任何中间件进行编码。最好的方法是什么?
按照代码:
的index.php
<?php
define('ROOT', dirname(__DIR__));
chdir(ROOT);
require 'vendor/autoload.php';
require 'src/Config/bootstrap.php';
require 'src/Config/routes.php';
$app->run();
bootstrap.php中
<?php
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
$app = new Application();
$app['serializer'] = function(){
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
return new Serializer($normalizers, $encoders);
};
$app['debug'] = true;
/*$app->before(function (Request $request) use ($app){
$request->query->
});*/
$app->after(function (Request $request, Response $response) use ($app){
//var_dump($response);
$response->headers->set('Content-Type', 'application/xml');
return $response;
});
return $app;
routes.php文件
<?php
$app->mount('/classificados', require 'src/App/Controllers/ClassificadosController.php');
ClassificadosController.php
<?php
use Symfony\Component\HttpFoundation\Response;
$classificados = $app['controllers_factory'];
$classificados->get('/', function() use ($app) {
$post = array(
'title' => 'Titulo',
'body' => 'corpo',
);
$serializeContent = $app['serializer']->serialize($post, 'xml');
return new Response($serializeContent, 200);
});
return $classificados;
构建逻辑以动态化客户端的响应格式(json或xml)的最佳方法是什么?