Search code examples
phpenvironment-variablesbase-urlmezzio

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/. Part of the API responses needs to send out its base_url. So I am trying to find a way to dynamically collect the base_url and add it to my response.

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. 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.


Solution

  • zend-http is not used in expressive, it's for zend-mvc. In expressive PSR-7 HTTP message interfaces are used and by default this is handled in 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

    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).