On laravel site I defined a facade based on LoggedUserService with Interface class, whicj looks like :
<?php
namespace AppLibraryFacades;
use AppLibraryServicesInterfacesLoggedUserInterface;
use IlluminateFoundationAuthUser as Authenticatable;
class LoggedUserFacade
{
public static function getAvatarHtml(?string $customClass = '', bool $showPermissions = false): string
{
$loggedUserInterface = app(LoggedUserInterface::class);
return $loggedUserInterface->getAvatarHtml(customClass: $customClass, showPermissions: $showPermissions);
}
public static function checkUserLogged(): string
{
$loggedUserInterface = app(LoggedUserInterface::class);
return $loggedUserInterface->checkUserLogged();
}
public static function getLoggedUser(): Authenticatable|null
{
$loggedUserInterface = app(LoggedUserInterface::class);
return $loggedUserInterface->getLoggedUser();
}
}
I defined several public static functions and wonder if there is a way to make one app bind calling, not in any static method I have above ?
"laravel/framework": "^10.48.7",
"php": "8.2",
Thanks in advance!
Attempt To Fix :
No, I got error :
Constant expression contains invalid operations
with such declaration.
I tried to init in __construct method :
class LoggedUserFacade
{
private static $loggedUserInterface;
public function __construct()
{
// die("IF UCOMMENTED - IS NOT CALLED");
self::$loggedUserInterface = app(LoggedUserInterface::class);
}
public static function getAvatarHtml(?string $customClass = '', bool $showPermissions = false): string
{
return self::$loggedUserInterface->getAvatarHtml(customClass: $customClass, showPermissions: $showPermissions);
}
But this __construct method is not called…
2
Answers
You can use a facade like this :
You have to create a service provider
LoggedUserServiceProvider.php
:Assuming that the service that implement
LoggedUserInterface
isLoggedUserService
.And don’t forget to register your service provider :
For the usage you simply do it like this :
You can actually implement your own facade using a Laravel’s facade
You can then use the facade by just using method names defined in
LoggedUserInterface
e.g.Laravel will handle injecting the interface as a singleton based on how you’ve bound it in the DI container.