Search code examples
phpzend-framework2viewhelper

Zend framework 2 get baseUrl from console controller


I tried to find a way to get base url of mixed (http + CLI) application. CLI is used to do some regular notifications, where app url is used.

I tried this, but it returns me only "http://"

print_r($this->getEvent()->getApplication()->getServiceManager()->get('ViewHelperManager')->get('ServerUrl')->__invoke());

Solution

  • This does not work for console requests. The serverUrl is extracted from the http request object (Zend\Http\Request), since a console request is wrapped in a console request object (Zend\Console\Request) this information won't be available for such requests.

    You can define (hardcode) an url in a global config or a constant and use this instead.

    For example add a host.config.local file to your application/config/autoload folder:

    <?php
    
    return array(
        'hostname' => 'http://www.example.com'
    );
    

    Now you can get your hostname from your service manager:

    $config = $serviceManager->get('config');
    $hostName = $config['hostname'];