[英]How to get the base url Programatically in zend expressive?
I am working on an API application that will be run in different domains: http://example.com/ , http://sub.example.com/ , http://example-another.com/ . 我的工作将在不同的域上运行的API应用程序: http://example.com/ , http://sub.example.com/ , http://example-another.com/ 。 Part of the API responses needs to send out its base_url .
API响应的一部分需要发送其base_url 。 So I am trying to find a way to dynamically collect the base_url and add it to my response.
因此,我试图找到一种动态收集base_url并将其添加到响应中的方法。
I have a factory to initiate the action handler as follows: 我有一个工厂来初始化动作处理程序,如下所示:
class TestHandlerFactory
{
public function __invoke(ContainerInterface $container) : TestHandler
{
return new TestHandler();
}
}
Then my action handler is as follows: 然后我的动作处理程序如下:
class TestHandler implements RequestHandlerInterface
{
public function __construct()
{
...
}
public function handle(ServerRequestInterface $request) : ResponseInterface
{
...
}
}
I am new to Zend world and I found the https://github.com/zendframework/zend-http/blob/master/src/PhpEnvironment/Request.php probably a potential solution of my problem. 我是Zend世界的新手,我发现https://github.com/zendframework/zend-http/blob/master/src/PhpEnvironment/Request.php可能是我的问题的潜在解决方案。 However, I do not how to get that PHP-Environment object (or any other object that help me grab the base url) in the factory or handler class.
但是,我没有如何在工厂或处理程序类中获取该PHP-Environment对象(或帮助我获取基本URL的任何其他对象)。
zend-http is not used in expressive, it's for zend-mvc. zend-http不用于表达,它用于zend-mvc。 In expressive PSR-7 HTTP message interfaces are used and by default this is handled in zend-diactoros .
在具有表现力的PSR-7中,使用HTTP消息接口 ,默认情况下,此消息在zend-diactoros中处理。
class TestHandler implements RequestHandlerInterface
{
public function handle(ServerRequestInterface $request) : ResponseInterface
{
// Get request URI
$uri = $request->getUri();
// Reconstruct the part you need
$baseUrl = sprintf('%s://%s', $uri->getScheme(), $uri->getAuthority());
}
}
More info can be found here: https://github.com/zendframework/zend-diactoros/blob/master/src/Uri.php 更多信息可以在这里找到: https : //github.com/zendframework/zend-diactoros/blob/master/src/Uri.php
EDIT: You cannot grab the request details in the factory itself. 编辑:您不能在工厂本身中获取请求的详细信息。 This can only be done in Middleware or Handlers (which are sort of a middleware).
这只能在中间件或处理程序(属于中间件)中完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.