簡體   English   中英

如何在zend Express中以編程方式獲取基本URL?

[英]How to get the base url Programatically in zend expressive?

我的工作將在不同的域上運行的API應用程序: http://example.com/http://sub.example.com/http://example-another.com/ API響應的一部分需要發送其base_url 因此,我試圖找到一種動態收集base_url並將其添加到響應中的方法。

我有一個工廠來初始化動作處理程序,如下所示:

class TestHandlerFactory
{
    public function __invoke(ContainerInterface $container) : TestHandler
    {

        return new TestHandler();
    }
}

然后我的動作處理程序如下:

class TestHandler implements RequestHandlerInterface
{
    public function __construct()
    {
        ...
    }
    public function handle(ServerRequestInterface $request) : ResponseInterface
    {

       ...
    }
}

我是Zend世界的新手,我發現https://github.com/zendframework/zend-http/blob/master/src/PhpEnvironment/Request.php可能是我的問題的潛在解決方案。 但是,我沒有如何在工廠或處理程序類中獲取該PHP-Environment對象(或幫助我獲取基本URL的任何其他對象)。

zend-http不用於表達,它用於zend-mvc。 在具有表現力的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());
    }
}

更多信息可以在這里找到: https//github.com/zendframework/zend-diactoros/blob/master/src/Uri.php

編輯:您不能在工廠本身中獲取請求的詳細信息。 這只能在中間件或處理程序(屬於中間件)中完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM