Reduce code duplication with static functions
2023-12-21 21:57 WIB - Hendrik Lie
There are plenty of codes doing the exact same things on both
App\Http\Controllers\Controller and
App\Providers\AppServiceProvider, so why not make them
exactly the same? In this update, we replace various reusable functions
in AppServiceProvider with static functions from
Controller. Among them are the following functions:
$getConfig()$fetchPost()$carbon()- And many more.
So for example in our Controller we have:
// File: app/Http/Controllers/Controller.php
public static function fetchPagesConfigByCode($code)
{
$config = PagesConfig::select(
'id',
'code',
'page_class',
'page_title',
'page_layout',
'is_editor')
->where('code',$code)
->first();
return $config;
}Then the corresponding anonymous function in
AppServiceProvider is:
$Controller = 'App\Http\Controllers\Controller';
$fetchPagesConfigByCode = "$Controller::fetchPagesConfigByCode";Therefore it simplifies code maintenance, as we don’t have to ensure
that those functions are updated on both files. Any improvements and
updates can then only be updated from Controller, and it
would automatically be reflected on AppServiceProvider.