Skip to content

Instantly share code, notes, and snippets.

@gjhuerte
Last active February 19, 2020 00:32
Show Gist options
  • Save gjhuerte/8921d38eb0af8e219923d2f7d6ef9f4a to your computer and use it in GitHub Desktop.
Save gjhuerte/8921d38eb0af8e219923d2f7d6ef9f4a to your computer and use it in GitHub Desktop.
Laravel Facades

Create a class and bind it to service container to initialize it

<?php
    class Fish 
    {
        public function swim()
        {
            return 'swimming';
        }

        public function eat()
        {
            return 'eating';
        }
    }
    
    app()->bind('fish', function () {
        return new Fish;
    });

Create a class and bind it to service container to initialize it

    class Bike
    {
        public function start()
        {
            return 'starting';
        }
    }

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

Create base facade, resolve it in the container and call the function you want to access

    class Facade
    {
        public static function __callStatic($name, $arguments)
        {
            return app()->make(static::getFacadeAccessor())->$name();
        }

        protected static function getFacadeAccessor() {}
    }

Create a facade for the two class above for us to call it statically

    class FishFacade extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'fish';
        }
    }

    class BikeFacade extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'bike';
        }
    }

    return [
        'fish' => FishFacade::eat(),
        'bike' => BikeFacade::start(),
    ];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment