If you look at the list, you will see functions like app
, config
, response
, and so on.
Maybe you are thinking why won't you use these functions? They are a part of the framework.
If you look at the code for the helpers most of the time they are syntactic sugar for calling facade classes.
Look at this controller;
class HomePageController {
public function __invoke() {
if(!auth()->hasUser()) {
return redirect()->route('login');
}
$user = auth()->user();
$timezone = config('app.timezone');
$api = resolve('HelpSpot\API');
// do something with the variables
return view('homepage');
}
}
If you written this controller with facades, you get;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
class HomePageController {
public function __invoke(Auth $auth, Redirect $redirect, Config $config, App $app, View $view) {
if(!$auth::hasUser()) {
return $redirect::route('login');
}
$user = $auth::user();
$timezone = $config::get('app.timezone');
$api = $app::get('HelpSpot\API');
// do something with the variables
return $view::make('homepage');
}
}
As you can see using facades is not a lot more code. I disregard the imports because they are handled by your IDE.
Adding the facade classes as parameters of a function has multiple benefits over using the helper functions.
You know exactly which facade you are using. Did you know the resolve function is using the App facade? The resolve function is syntactic sugar for the app function if you look at the code.
Your functions are easier to mock. So instead of needing end to end tests, you can use unit tests.
When you see the dependencies, you are going to be warned faster that the function is doing a lot of things. And you can figure out a way to prevent this.
I was thinking why are the helpers still in the framework. And the only idea I had is, because it is a remnant of the time intellisense wasn't as good as it is now. The helpers are easier to remember for the people that write code without intellisense.
Now you just type a few letters and you get a list of classes you can to use. Your IDE imports the class to make the parameter types shorter. And you type a double colon or an arrow and you get a list of methods you can use.
So instead of using your brain to memorize helpers, let you code editor do that work for you. And you concentrate on the things you are building.
Top comments (0)