Can I get the domain of a request with silex

1.1k views Asked by At

I want to create one silex application that listens to requests to routes to two domains. Depending on the domain the response should be different. I know I can simply inject a Request object and use that to get the host from, but I'd like to use a nicer way like this, but using Silex.

Is this possible and if so: how?

2

There are 2 answers

0
puppyFlo On BEST ANSWER

This is not a bad question - I ended up here looking for a quick answer myself.

It turns out to be rather easy - you just need your instance of the Symfony Request which provides access to the following method:

$base_url = $request->getHost();
$app['monolog']->notice('Base path result', ['base_url' => $base_url])

My result:

[2016-02-19 10:04:15] api.INFO: Base path result [] {"base_url":"api-test.xonadu.com"}

I hope that's useful :)

2
mTorres On

It should be as easy as calling the host() method for each route (you can also do that on an entire ControllerCollection instance for all its routes) like so:

<?php

// initialization, etc.

$app->get('/', function() {
  return new Response("Only from my.host.com!");
})
->host('my.host.com')
;