Reputation: 9302
So I'm developing a site. It's being hosted on one dedicated server, but will have several domain names pointing to a single Laravel 5.1 installation.
Each domain name (not including the subquery) is owned by a Client model. Each client can have multiple sites, which are defined by the subdomain.
For example, I own phil-cross.co.uk
. So in my client table I have a record for a client with the domain phil-cross.co.uk
.
I then have multiple records in my Sites
table, for www.phil-cross.co.uk
or blogs.phil-cross.co.uk
and so on.
The application can also manage other domains. So I might have another client with the domain name joe-bloggs.com
.
At the moment my laravel application can correctly determine the client by the domain name, and the site by the subdomain, but the way it does it is quite messy.
At the moment, I have a service provider which has a static client
and site
property, and the boot method loads the current client and site and stores them within this service provider. I then have a facade with some helper methods which can access the client and site properties from the service provider.
I want to, at any given time within the life of the application to be able to access the Client and Site model for the current site.
Is there a best practice within laravel for storing globally accessible models? Is my Service Provider / Facade way of currently doing it acceptable or should it be middleware? Is there other ways of doing it that I'm unaware of?
Tldr:
How can I create a single instance of a model, and access it at any time, and anywhere within the laravel application.
Upvotes: 1
Views: 137
Reputation: 24661
I think using a service provider is the correct solution, just not how you seem to be going about it. Leverage the IoC to create a singleton object, since a singleton is just what you want: an object that is resolved once and only once during the lifetime of the application:
class SomeServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('SomeClass', function() {
$myObj = new SomeClass;
$myObj->determineClient();
return $myObj;
});
}
}
Then later on, somewhere else in your application, you can do this:
$myObj = app()->make('SomeClass');
echo $myObj->client;
The benefits of using this approach is that, if SomeClass
changes and dependencies to that class are added, you only have to change how that object is constructed in a single spot and those changes will automatically take effect everywhere that the object is being used from.
Upvotes: 2