Laravel Facade
In Laravel, a facade is a way to access complex features with a simple, easy-to-remember name. For example, Request::all()
retrieves all the input data from the current HTTP request without worrying about how Laravel handles this process.
It is easy to use and makes your code easier to understand. On the other hand facades can make it difficult to see the dependencies of your class and they can be tempting to overuse them. They can be useful in certain situations, but they should not be used as a substitute for dependency injection. When a class uses many facades, it can become difficult to see all the things that class depends on. This can lead to a class doing too many things and you should consider separate the responsibilities.
Now let’s see how fast and simple we can implement our own facade in a courses management Laravel application. Nothe that this is just for demo purpose, not a real life example.
- First we are creating a service class that handles course-related logic.
2. We need to register our service in Laravel’s service container and make it available for dependency injection and facades and we are passing the courseService alias to resolve our service.
app/Providers/AppServiceProvider.php
3. Create the Facade. Our class extends the Facade
class and define a getFacadeAccessor
method that will return the alias (or key) that we used when we registered our service, in this case courseService.
app/Facades/CourseFacade.php
4. Now, we can use CourseFacade
in our controller.
app/Http/Controllers/CourseController.php
This approach encapsulates business logic into a dedicated service and what we basically did si to hide hide our service behind a facade.