laravellaravel-facade

How in facade wrapper to make 1 one app bind calling?


On laravel site I defined a facade based on LoggedUserService with Interface class, whicj looks like :

<?php

namespace App\Library\Facades;

use App\Library\Services\Interfaces\LoggedUserInterface;
use Illuminate\Foundation\Auth\User 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...


Solution

  • You can actually implement your own facade using a Laravel's facade

    namespace App\Library\Facades;
    
    use App\Library\Services\Interfaces\LoggedUserInterface;
    use Illuminate\Support\Facades\Facade;
    
    
    class LoggedUserFacade extends Facade {
       protected static function getFacadeAccessor() {
           return LoggedUserInterface::class;
       }
    }
    

    You can then use the facade by just using method names defined in LoggedUserInterface e.g.

       LoggedUserFacade::checkUserLogged();
    

    Laravel will handle injecting the interface as a singleton based on how you've bound it in the DI container.