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
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);
}
}
SmartLoggerFacade.php
<?php
namespace App\SmartLogger;
use Illuminate\Support\Facades\Facade;
class SmartLoggerFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'smartlogger';
}
}
lets make service provider
php artisan make:provider SmartLoggerServiceProvider
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()
{
//
}
}
Now open config\app.php and add this lines in it
Add it in "providers" array
...
App\Providers\SmartLoggerServiceProvider::class
Add it in "aliases" array
...
'Smartlogger' => App\SmartLogger\SmartLoggerFacade::class
Now lets test it :)
Add this code in your controller
SmartLogger::log("Hi");
And add this in top of your controller
use App\SmartLogger\SmartLoggerFacade as SmartLogger;
Top comments (0)