Using Laravel Facades to Improve Code Readability
Laravel Facades allows you to make the usage of classes more readable and understandable. In this article, we will show you how to create a Facade and how to use it with a route and controller.
First, you need to create a folder app/Facades
. In this folder, you will store your Facade classes. Then, create a file app/Facades/MyFacade.php
and write a class like this:
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;class MyFacade extends Facade { protected static function getFacadeAccessor() {
return 'myclass';
}
}
In this class, you have to define the getFacadeAccessor
method. This method specifies which class the Facade class represents. For example, we used the name 'myclass'.
Then, open the config/app.php
file and add this line in the aliases
array:
'MyFacade' => App\Facades\MyFacade::class,
This line defines the name of your Facade class and matches it with the real class.
Now, you can use your Facade class. For example, in a route:
Route::get('/', function () {
MyFacade::someMethod();
return view('welcome');
});
or in a controller:
class MyController extends Controller
{
public function index()
{
MyFacade::someMethod();
return view('welcome');
}
}
In this way, you can perform actions without knowing the name or details of the real class by using only the Facade class. This makes your code more readable and understandable.
The title and content of this article were created with “ChatGPT”.
Tolga Karabulut
tolga.karabulut@airalo.com
Airalo GSM | Senior PHP Developer