我已被分配到一个项目,该项目需要包括Symfony组件才能重新组织其业务逻辑。但是,我对Symfony HTTP基础文档感到困惑。希望这里有人可以帮助我解释一下此组件如何处理用户Http请求和响应。
基本上,我在项目中所做的是:
具有PHP页面会创建带有请求的URL和方法
使用ApiRouter将代码定向到所需的控制器
在控制器内,它将HTTP请求发送到服务器,并根据请求URL将响应转换为Symfony Response对象。
location.php
class GetLocation
{
public function __construct($q)
{
$request = Request::create('location?v=full&q=' .
urlencode($q), 'GET'); //simulates a request using the url
$rest_api = new RestApi(); //passing the request to api router
$rest_api->apiRouter($request);
}
}
ApiRouter.php
//location router
$location_route = new Route(
'/location',
['controller' => 'LocationController']
);
$api_routes->add('location_route', $location_route);
//Init RequestContext object
$context = new RequestContext();
//generate the context from user passed $request
$context->fromRequest($request);
// Init UrlMatcher object matches the url path with router
// Find the current route and returns an array of attributes
$matcher = new UrlMatcher($api_routes, $context);
try {
$parameters = $matcher->match($request->getPathInfo());
extract($parameters, EXTR_SKIP);
ob_start();
$response = new Response(ob_get_clean());
} catch (ResourceNotFoundException $exception) {
$response = new Response('Not Found', 404);
} catch (Exception $exception) {
$response = new Response('An error occurred', 500);
}
我希望知道的是我对逻辑的理解是否正确?方法Request:createFromGlobal表示什么,这与Request:create(URL)有什么区别
请让我知道我的问题是否需要更具体。
答案 0 :(得分:0)
首先,您的问题更简单:
Request::createFromGlobals()
将基于一些PHP全局变量创建请求,例如$_SERVER
,$_GET
和$_POST
,这意味着它将根据“我们”所在的当前请求(即触发我们应用程序的用户请求)创建一个请求。另一方面,Request::create()
将在不应用此上下文的情况下建立一个“新”请求,这意味着您必须自己传递某些信息,例如路径和HTTP方法。
现在有关您的代码以及它是否有效。简短的答案可能不是。在GetLocation中,您将创建一个新请求和一个新路由器,并在控制器内部创建一个路由,然后将其添加到路由器中。这意味着除非在GetLocation之前执行控制器代码,否则路由将在路由器中不可用,这意味着永远不会调用控制器。
您可能想研究一下以下系列:Create your own PHP Framework,在symfony文档中,尤其是The HttpFoundation Component之后的部分。希望这会为您清除一切。