I'm creating a multi-domain application, so my application is served from multiple domains. Each domain has its own configuration like this:
app/config/domains.php
return [
'www.domain1.com' => [
'name' => 'UK',
'default_language' => 'en',
'languages_available' => ['en'],
'email' => '[email protected]',
],
'www.domain2.com' => [
'name' => 'France',
'default_language' => 'fr',
'languages_available' => ['fr', 'en'],
'email' => '[email protected]',
],
]
I want to be able to access a $domain variable from anywhere in my application that will give me the configuration for the current domain that is being used to access the application.
Here's how I've done it so far.
I've created a very simple Domain class which takes an array and converts it to an object as follows:
app/domain.php
class Domain {
public function __construct($domain)
{
foreach ($domain as $key => $value)
$this->$key = $domain;
}
}
}
Then I've created a DomainServiceProvider.php and in the boot method I do:
$host = request()->getHttpHost();
$this->domain = isset(config('domains')[$host]) ? config('domains')[$host] : [];
app->singletone('App/Domain', function($app) {
return new Domain($this->domain);
});
Then in any of my controllers I can do:
class HomeController extends Controller
{
public function show(Domain $domain)
{
if ($domain->name == 'UK') {
// Do something here
}
// Return the view and pass $domain instance
return view('show', [
'domain' => $domain,
]);
}
}
How does this seem? It works OK but I'm wondering if there is a more simple way? In particular is there a way og doing it without creating the Domain class which seems a little redundant.