Duy Dinh - 2016-03-23

How To Create Facade On Laravel 5.1
Posted on 9 months ago

Here is step by step to create facade on laravel 5.1

Create PHP Class File.
Bind that class to Service Provider
Register that ServiceProvider to Config\app.php as providers
Create Class which is this class extends to Illuminate\Support\Facades\Facade
Register point 4 to Config\app.php as aliases
Step 1 - Create PHP Class File, for example in App\Classes\Someclass.php

namespace App\Classes;

class Someclass {
public function get($data = [])
{
echo "foo";
}
}
Step 2 - Bind that class to Service Provider

In case i create a new serviceprovider by execute

php artisan make:provider 'SomeclassServiceProvider'
then add

    App::bind('someclass', function()
    {
        return new \App\Classes\Someclass;
    });

Like so

namespace App\Providers;

use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;

class SomeclassServiceProvider extends ServiceProvider
{
/
* Bootstrap the application services.

* @return void
/
public function boot()
{
//
}

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    App::bind('someclass', function()
    {
        return new \App\Classes\Someclass;
    });
}

}

Step 3 - Register that ServiceProvider to Config\app.php as providers

     /*
     * Application Service Providers...
     */
    App\Providers\SomeclassServiceProvider::class,

Step 4 - Create Class which is this class extends to Illuminate\Support\Facades\Facade

For Example I create this class in App\Facades\Someclass.php

namespace App\Facades;
use Illuminate\Support\Facades\Facade;

class Someclas extends Facade{
protected static function getFacadeAccessor() { return 'someclass'; }
}
Step 5 - Register point 4 to Config\app.php as aliases

'Someclass' => App\Facades\Someclass::class
Testing

On App\Http\routes.php create single route

Route::get('/', function(){
Someclass::get();
});
Then check on your browser