Create and Use Custom Facades in Laravel

Lets create a class called Test

class Test{
    public function testfunction(){
        return 'testfunctioning';
    }
    public function test2()
    {
        return 'testing2';
    }
}

And bind the class .

app()->bind('Test',function (){
    return new Test();
});

Create a new TestFacade class.

class TestFacade
{
    public static function __callStatic($name,$args){
        //app()->make and resolve are same
        //  return app()->make('fish')->$name();
        return resolve('test')->$name();
    }
}
dd(TestFacade::testfunction());

This will return

Testfunctioning

So what we are doing here?

First, we constructed a standard class. The class is then bound in Container. However, binding is not required because Laravel will bind it automatically. Then, in the TestFacade class, we create a magic method called __callStatic, where $name is the function and $args is an array of arguments. The method is then resolved and returned.

__callStatic:: When you call a static method that does not exist on the class, PHP automatically runs the __callStatic () magic function to construct that method as static.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top