Bootstrap the making of Laravel Facades

Submitted by Mahmoud_Zalt - 8 years ago

There are three components to generating a Facade: 1 - The wanna be Facade Class, (the class that needs to become a facade). 2 - The Facade required Class, (which tells Laravel which registered class it pertains to) 3 - A Service Provider, (which registers the Facade class in the App container)

1. the wanna be Facade Class:
example:


<?php namespace Moubarmij\Services\ModelsServices;

 

class AuthenticationService extends MoubarmijService implements AuthenticationServiceInterface{


    /**
     * @param $email
     * @param $password
     *
     * @return mixed
     */
    public function login($email, $password)
    {
        return Sentry::authenticate([
            'email'    => $email,
            'password' => $password,
        ]);
    }

    /**
     * @return mixed
     */
    public function logout()
    {
        return Sentry::logout();
    }
    
}









2. the required class for the facade to work:
example:


<?php namespace Moubarmij\Facades;

 
use Illuminate\Support\Facades\Facade;

/**
 * Class AuthenticationServiceFacade
 * @package Moubarmij\Services\ModelsServices
 */
class AuthenticationServiceFacade extends Facade{

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'authentication_service'; }


}
note: authentication_service can be anything you want (its the name of the component registered in the IOC)










3. the service provider 

example:

<?php namespace Moubarmij\Providers;

 
use Illuminate\Support\ServiceProvider;

/**
 *  A service provider for the Authentication Service
 *
 * Class AuthenticationServiceSP
 * @package Moubarmij\Providers
 */
class AuthenticationServiceSP extends ServiceProvider {

    /**
     * bind interfaces
     *
     * @return void
     */
    public function register()
    {
        // Register 'authentication_service' instance container to our AuthenticationService object
        $this->app['authentication_service'] = $this->app->share(function($app)
        {
            return $app->make('Moubarmij\Services\ModelsServices\AuthenticationService');
        });

        // Shortcut to auto add the Alias in app/config/app.php
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('AuthenticationService', 'Moubarmij\Facades\AuthenticationServiceFacade');
        });

    }
}