phplaravellaravel-facade

Adding Facades before namespace in Laravel , How it works?


Okay there are questions about the same topic before but they don't help to fully understand this topic

SO SuggestionFirst
SO Suggestion Second

All the code is just to illustrate the situation, So this is the structure

A helper function which does something

namespace App\Helpers;

class Pets{

    public function limit($string,$limit,$start = 0){
        return substr($string,$start,$limit);
    }
}

Now in order to use this helper, since it's a class so i need to create an object like this


CODE SAMPLE FIRST

namespace App\Objects;

use App\Helpers\Pets;

class User{

    public function getShortUserName(){
        $name = auth()->user()->first_name.' '.auth()->user()->last_name;
        $pet = new Pets;
        return $pet->limit($name,10);
    }
}

But somewhere I got to know that if you add Facades before your namespace, you can call the function statically even if they are non static function like this


CODE SAMPLE SECOND

namespace App\Objects;

use Facades\App\Helpers\Pets;

class User{

    public function getShortUserName(){
        $name = auth()->user()->first_name.' '.auth()->user()->last_name;
        return Pets::limit($name,10);
    }
}

Now what I want to know is I have 2 sample codes with namespace as follows

use App\Helpers\Pets;
use Facades\App\Helpers\Pets;

By adding the Facades I can call the function statically but how, that's not a valida namespace in my app What laravel doing behind the scene, I am so confused

Thank you for your time ;)


Solution

  • What you are describing is Laravels Real-Time Facades.

    You can find documentation of the functionality here: https://laravel.com/docs/6.x/facades#real-time-facades