Facades in Laravel
What are Facades in Laravel?
Facades give you an easy way to use classes from the service container without needing to resolve them manually each time. Even laravel provides you some in-build facades like caching, routing, sessions etc.
Facades are "static proxies" to classes that is available in service container.
(static proxies means, proxies acts like middleman and it catches the static call and forward to your actual object & static means you called static methods of that facade class)
Why use Facades?
- Readable Syntax
- Quick Access
- Centralized Logic
Below is example of FileUpload so get to know how you can use the Facades in it,
Create the files class at following Location app/Facades/FileUpload.php & app/Services/CommonFileUpload.php
app/Facades/FileUpload.php
<?php
declare(strict_types=1);
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class FileUpload extends Facade
{
protected static function getFacadeAccessor(): mixed{
return 'commonfileupload';
}
}
app/Services/CommonFileUpload.php
<?php
declare(strict_types=1);
namespace App\Services;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class CommonFileUpload
{
/**
* Upload File
*
* @param [type] $file
*/
public static function uploadFile(string $folder_name, mixed $file): string{
$fileName = time().rand(10000, 99999).'.'.$file->getClientOriginalExtension();
Storage::disk('public_path')->putFileAs($folder_name, $file, $fileName);
return asset('uploads/'.$folder_name.'/'.$fileName);
}
}
Register in AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/public function register(): void{
$this->app->singleton('commonfileupload', function ($app) {
return app(CommonFileUpload::class);
});
}
}
How to use in Controller?
FileUpload::uploadFile('upload', $request->file);