php - Is it possible to intiailize variables in a constructor for a Laravel facade?
If I am creating a custom facade and want to have certain variables initialized at every instance of using customFacade::doSomething()
, is that possible? My main purpose for doing this is to be able to store variables that are other objects and call functions on them directly. Example being customFacade::client->send()
where in this case client
is the initialized variable of an object with a send()
function. I am aware I can have a function client()
instead and return the a new instance of the object so the send()
goes through, but I'd still like to know if its possible the other way.
In a normal class I can do below, but it doesn't work on facades.
$protected client;
public function __construct()
{
$this->client = new instanceOfObject();
}
Answer
Solution:
Since a Facade uses static functions you could only do something like
public static $client = null;
public static function init() {
if(self::$client == null)
self::$client = new instanceOfObject();
}
// somewhere else
customFacade::init();
customFacade::client->send();
Answer
Solution:
Laravel will resolve all the dependencies you need out of the service container, in the class constructor which underlies your facade. A toy example to show my point, will have UserRepository
resolved in the DateService
, and therefore the Dates
facade.
Usage like,
return view('profile' => [
...
'time' => Dates::loggedLocal(),
...
]);
DatetimeService.php
class DatetimeService
{
private $userRepository;
public function __construct(
UserRepository $userRepository
) {
$this->userRepository = $userRepository;
}
/**
* Get the logged in users local time
*
* @return Carbon
*/
public function loggedLocal() : Carbon
{
$user = $this->userRepository->current();
return Carbon::now()->setTimezone($user->timezone);
}
Dates.php
class Dates extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'date-service'; }
}
DateServiceProvider.php
class DateServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('date-service', function()
{
return new DateTimeService;
});
}
}
Source