Laravelで自作のヘルパ関数を作成したり既存のヘルパ関数をカスタマイズしたい時などの方法を備忘録で残しておきます。
自作のヘルパ関数を作成する
自作のヘルパ関数は任意の作成したヘルパ関数をautoloadで読み込むと作ることができます。
まずはapp/helpers.phpなど任意の場所にファイルを用意します。
<?php declare(strict_types=1);
if (! function_exists('hogehoge')) {
/**
* @return string
*/
function hogehoge(): string
{
return 'ほげほげ';
}
}
次にcomposer.json
の autoload.files
に先ほど作成したファイルを追記します。
"autoload": {
"files": [
"app/helpers.php"
],
},
composer dump-autoloadでオートローダーを更新します。
composer dump-autoload
標準のヘルパ関数をカスタマイズしてオーバーライドする
今回はLaravel標準で用意されている多言語化に対応するヘルパ関数をカスタマイズしたいと思います。
ヘルパ関数はvendor/laravel/framework/src/Illuminate/Foundation/helpers.phpにあります。
以下は一部抜粋しています。
if (! function_exists('__')) {
/**
* Translate the given message.
*
* @param string|null $key
* @param array $replace
* @param string|null $locale
* @return string|array|null
*/
function __($key = null, $replace = [], $locale = null)
{
if (is_null($key)) {
return $key;
}
return trans($key, $replace, $locale);
}
}
function_existsによって関数がすでに定義済みかどうかを判定しているので、カスタムしたいヘルパ関数をLaravel標準のヘルパ関数より先にautoloadで読み込ませてあげれば上書きができそうです。
ヘルパ関数をカスタマイズ
if (!function_exists('__')) {
function __($key = null, $replace = [], $locale = null)
{
if (is_null($key)) {
return $key;
}
$hasLang = \Illuminate\Support\Facades\Lang::hasForLocale($key);
if (config('app.env') !== 'production' && $hasLang !== true) {
return "辞書定義がありません!";
}
return trans($key, $replace, $locale);
}
}
オートローダーファイルを書き換える
まずはオートローダーを書き換えるコマンドファイルを作ってあげます。
php artisan make:command OverrideHelperCommand
app/Console/Commands/OverrideHelperCommand.php
が作成されるので下記のようにcomposerのオートローダファイルを書き換えるロジックを書いてあげます。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class OverrideHelperCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'override-helper:autoload';
/**
* The console command description.
*
* @var string
*/
protected $description = 'app/helpers.php を先読みさせる';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(): void
{
$autoloadPath = base_path('vendor/autoload.php');
$helperPath = app_path('helpers.php');
// オートローダーのファイル内容を読み込む
$before = file_get_contents($autoloadPath);
// 先に自作ヘルパファイルを一番最初に読み込むようにする
$after = str_replace('<?php' . PHP_EOL, "<?php require_once '$helperPath';" . PHP_EOL, $before);
// オートローダーを上書きする
file_put_contents($autoloadPath, $after);
}
}
次にcomposer dump-autoloadが呼ばれた際に実行されるようcomposer.jsonに組み込みます。
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi",
"@php artisan override-helper:autoload" //追記
],
composer dump-autoload
これで自作のhelper関数が一番最初に読み込まれるようになりました。