Laravelで共通関数作成、個人メモ。
環境
- Laravel 10.4.1
- PHP 8.2.4
作業
- \app\Libs
に
Common.php
を作成。(フォルダ名、ファイル名は任意)
下記では例として、「get_img_path」関数を作成。
Common.php
<?php
namespace App\Libs;
class Common
{
//ユーザーの画像パスを返す
public static function get_img_path($db_img){
if($db_img == 'noimage.jpg'){
$img = '/storage/default/noimage.jpg';
}else{
$img = '/storage/todo/' . $db_img;
}
return $img;
} //end funtion index
}
- \config\app.php 最下部に下記追加
app.php
(略)
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
// 'aliases' => Facade::defaultAliases()->merge([
// // 'ExampleClass' => App\Example\ExampleClass::class,
// ])->toArray(),
'aliases' => Facade::defaultAliases()->merge([
'Common' => App\Libs\Common::class,
])->toArray(),
※エイリアスの説明部分の日本語訳は
このクラス エイリアスの配列は、このアプリケーションの起動時に登録されます。 ただし、エイリアスは「遅延」ロードされるため、パフォーマンスを妨げないため、好きなだけ登録してください。
- コントローラーファイル内で共通関数を使用。上部にuse宣言は不要。この例では
\Common::get_img_path()
で呼び出せる。
$img = \Common::get_img_path($user->img); //共通関数で画像パス取得