Define your own facade in laravel

azibom

Mohammad Reza

Posted on June 17, 2020

Define your own facade in laravel

In this article we want to know how can we define our own facade
and use it in our application

In this article I want to make SmartLogger class and try to use it with Facades so lets start

Create a directory in app and which has SmartLogger name and fill it like below

.
├── SmartLoggerFacade.php
└── SmartLogger.php

0 directories, 2 files
Enter fullscreen mode Exit fullscreen mode

SmartLogger.php

<?php

namespace App\SmartLogger;

class SmartLogger {
    public function log($text) {
        $path = storage_path('logs');
        $myfile = fopen("{$path}/SmartLog.txt", "a");
        fwrite($myfile, $text);
        fwrite($myfile, PHP_EOL);
        fclose($myfile);
    }
}
Enter fullscreen mode Exit fullscreen mode

SmartLoggerFacade.php

<?php

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

class SmartLoggerFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'smartlogger';
    }
}
Enter fullscreen mode Exit fullscreen mode

lets make service provider

php artisan make:provider SmartLoggerServiceProvider
Enter fullscreen mode Exit fullscreen mode

SmartLoggerServiceProvider.php

<?php

namespace App\Providers;

use App\SmartLogger\SmartLogger;
use Illuminate\Support\ServiceProvider;

class SmartLoggerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('smartlogger',function(){
            return new SmartLogger();
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

Now open config\app.php and add this lines in it

Add it in "providers" array

...
        App\Providers\SmartLoggerServiceProvider::class
Enter fullscreen mode Exit fullscreen mode

Add it in "aliases" array

...
        'Smartlogger'   =>  App\SmartLogger\SmartLoggerFacade::class
Enter fullscreen mode Exit fullscreen mode

Now lets test it :)

Add this code in your controller

SmartLogger::log("Hi");
Enter fullscreen mode Exit fullscreen mode

And add this in top of your controller

use App\SmartLogger\SmartLoggerFacade as SmartLogger; 
Enter fullscreen mode Exit fullscreen mode

Feel free to ask any questions :)

💖 💪 🙅 🚩
azibom
Mohammad Reza

Posted on June 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related