Helperクラスを使用したコードの細分化と祝日表示の実装

このQ&Aのポイント
  • Helperクラスを使用して外部classで計算させる方法を紹介します。
  • 祝日が該当する場合に表示するためのcsvファイルを読み込む方法を説明します。
  • これらの方法を使用することで、Viewのコードをより簡潔にすることができます。
回答を見る
  • ベストアンサー

更に細分化をしたいのですが。

以前、質問をさせて頂いた内容の続きになります。Helperクラスを作ってview側でinjectさせ表示をされることは出来ました。それでも、コードが長くなりますので更に細分化したいのですが、可能でしょうか? ①例えば前回質問させていただいた下記のコードのecho $sabunの$sabunを外部classで計算させてhelperに読み込ませるようなことを考えています。また②下記のようなクラスを用意してcsvファイルを読み込ませ祝日が該当すれば表示るようなことも可能でしょうか? ①一部抜粋 $ym = date("2022-04-22"); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $countdate=date('t',mktime(0,0,0,$tm,1,$ty)) for ($i = 0; $i < $countdate; ++$i) { $d = mktime(0, 0, 0, $tm, 16 + $i, $ty); //日付ごとの配列のキー $dd = date('Y-m-d', $d); foreach($e_all as $e_time){ if (in_array($dd, (array)$e_time->date_time)) { echo $e_time->start_time; echo $e_time->end_time; $sabun = (strtotime($e_time->end_time) - strtotime($e_time->start_time)) / 60; echo $sabun; ②祝日がcsvファイルの中に該当すれば表示する 一部抜粋 namespace App\Helpers; use \SplFileObject; class SyukuHelper { public function syukuLogic($d) { $file = new SplFileObject(storage_path("app/holiday.csv")); $file->setFlags(SplFileObject::READ_CSV); $exist_flg = false; foreach ($file as $line) { if (isset($line[1])) { $date = date("Y/m/d", strtotime($line[0])); $name = $line[1]; if ($date == date('Y/m/d', $d)) { echo '<td class="border border-gray-400 ..." align="center" bgcolor="lightblue">'.$name.'</td>'; $exist_flg = true; } } } //祝日一致なければ空欄 if ($exist_flg == false) { echo '<td class="border border-gray-400 ..." align="center" bgcolor="lightblue"></td>'; } どうぞよろしくお願い致します。

  • PHP
  • 回答数1
  • ありがとう数2

質問者が選んだベストアンサー

  • ベストアンサー
回答No.1

設計思想の問題なので、いかようにも管理しやすいように切り分ければよいと思います。 例えば、以下のように切り分けるのが良いのではないでしょうか。 ■App\Helpers\SyukuHelper これは、View(Blade)テンプレートで利用するためのいわば窓口である、という考え方。 ■App\Services\HolidayService これを祝日判定用のサービスとして機能させる。 ■で、実装 app/Helpers/SyukuHelper.php <?php namespace App\Helpers; use App\Services\HolidayService; class SyukuHelper { private $holiday; public function __construct() { $this->holiday = new HolidayService(); } public function syuku($d) { $currentDay = date('Y/m/d', $d); $result = $this->holiday->get($currentDay); if ($result !== null) { // 祝日判定だったら、なんかHTMLとか出力する echo '祝日のときのHTML' . $result['name']; } else { echo '平日のときのHTML'; } } } ?> app/Services/HolidayService.php <?php namespace App\Services; use SplFileObject; class HolidayService { private $holidays = []; public function __construct() { // どうせ総なめするし、使いやすいようにコンストラクタで計算結果の配列つくっとく $file = new SplFileObject(storage_path('app/holiday.csv')); $file->setFlags(SplFileObject::READ_CSV); foreach ($file as $line) { if (!isset($line[1])) continue; $date = date('Y/m/d', strtotime($line[0])); $name = $line[1]; $this->holidays[$date] = $name; } } public function get($d) { if (array_key_exists($d, $this->holidays) { // ファイルから作った連想配列のキーに該当の日付があった場合、祝日の名称を返す return ['name' => $this->holidays[$d]]; } else { return null; } } } ?> みたいな感じで切り分けられれば良いと思います。 このような感じにしておけば、View以外で、例えばコントローラなんかで祝日チェックしたい、とか言った場合にも、HolidayServiceだけ呼び出せば使えるわけですね。

iyumoyumo
質問者

お礼

いつも、ご回答ありがとうございます。 多分また、質問をさせていただく事になるかと思いますが よろしくお願い致します。

関連するQ&A

  • laravel controllerに記載したい

    以前、回答いただいた内容で現在view側に書いている内容が view側に記入してあると肥大化するのでcontroller側に書きたいのですが可能でしょうか?foreachで回しているのでviewにかくしかないでしょうか?もしも可能であればcontroller側へのデータの渡し方も教えていただけるとありがたいのですが。。。よろしくお願いします。 $ym = date("2022-04-22"); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $countdate=date('t',mktime(0,0,0,$tm,1,$ty));//4月の日数を計算 $goukei = 0; for ($i = 0; $i < $countdate; ++$i) { $d = mktime(0, 0, 0, $tm, 16 + $i, $ty); //日付ごとの配列のキー $dd = date('Y-m-d', $d); foreach($e_all as $e_time){ if (in_array($dd, (array)$e_time->date_time)) { echo $e_time->start_time; echo $e_time->end_time; $sabun = (strtotime($e_time->end_time) - strtotime($e_time->start_time)) / 60; echo $sabun; $goukei += $sabun; echo $goukei; } } }

    • ベストアンサー
    • PHP
  • 時間の加算(その2)php

    DBからある範囲の日付けの時間だけを取ってきて取ってきた時間の差分の累計を計算したいです。 例えば、4月16日から5月15日までのスタート時間とエンド時間を所得 させてエンド引くスタート、日々の差分を累計するようなことが実現したいです。 下記のように書いてデータだけは引っ張ってこれるようになったのですが加算方法が分かりません。ご教授いただけませんでしょうか? (ソース?php $ym = date("2022-04-22"); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $countdate=date('t',mktime(0,0,0,$tm,1,$ty));//4月の日数を計算 for ($i = 0; $i < $countdate; ++$i) { $d = mktime(0, 0, 0, $tm, 16 + $i, $ty); //日付ごとの配列のキー $dd = date('Y-m-d', $d); foreach($e_all as $e_time){ if (in_array($dd, (array)$e_time->date_time)) { echo $e_time->start_time;   echo $e_time->end_time; }} } ?> 因みにechoで表示されたデータは 09:00:00 20:00:00 08:00:00 18:00:00 09:00:00 19:10:00 となっていて 順番に登録してある4/20 のスタート時間、エンド時間 4/21のスタート時間、エンド時間4/22のスタート時間、エンド時間 の並びで取れています。よろしくおねがいします

    • ベストアンサー
    • PHP
  • コントローラーからview⇒helperへ値渡し

    Index.blade.phpを当月として、前月をlast.blade.php,次月をnext.blade.phpとして各1ヶ月分の勤務状況を表示しています。 Index.blade.phpを以前、教えていただいた通りHelper.phpとService.phpに切り出してIndex.blade.phpを軽くすることは出来ました。 last.balde.phpとnext.blade.phpも基本的には同じ作りにしたいと思っています。 処理をしている時点を起点にして、次月、前月に遷移する作りにしています。 Index.blade.php内で下記のコードを記載してlastとnextに$ymと$lastmonthを渡しています。 <a href="{{ route('user.last',['ym'=>$ym,'lastmonth'=>$lastmonth]) }}"><<先月</a> <a href="{{ route('user.next',['ym'=>$ym,'nextmonth'=>$nextmonth]) }}">次月>></a> (今回の問題) last.blade.phpをhelperとserviceに切り分けていないときは$ymと$lastmonthのデータ渡しが出来たのですが切り分けた途端$lasymonthと$ymと$mが認識出来ません。 エラ〜は例えば、lastmonthがundefinedみたいなエラ〜となります。 indexとlastのコントロラーは下記の通りです。 Controller一部抜粋 public function index(Request $request){ { $user= $request->user(); } $dt=Carbon::now(); $ym=$dt->format('Ym'); $lastm=$dt->subMonths(1); $nextm=$dt->addMonths(1); $lastmonth=$lastm->format('Ym'); $nextmonth=$nextm->format('Ym'); $tm=$dt->month; $ty=$dt->year; setlocale(LC_ALL, 'ja_JP.UTF-8'); $youbi=$dt->formatLocalized('%a'); $this_month_days=$dt->daysInMonth; $e_all = Kintai::where('user_id',Auth::user()->user_id)->get(); foreach ($e_all as $e_time) { } } return view('user.index',compact('e_all','user','point_actions','point_count','paterns','e_users','ym','lastmonth','nextmonth','tm','ty','this_month_days','const_rest_t')); } public function last(Request $request) { $e_all = Kintai::all(); $ym = $request->ym; $lastmonth = date("Ym",strtotime($ym."01"." -1 month ")); $nextmonth = date("Ym",strtotime($ym."01"." +1 month ")); $ly = date('Y',strtotime($ym.$lastmonth)); $m = date("n",strtotime($ym.$lastmonth)); return view('user.last',compact('lastmonth','e_all','ly','m','ym','nextmonth','paterns','e_users','point_count')); } (ここまでソース) 因みに上記の方法でlast.balde.php内で <?php $ym=$lastmonth; echo $lastmonth; $lastmonth = date("Ym",strtotime($ym."01"." -1 month ")); $nextmonth = date("Ym",strtotime($ym."01"." +1 month ")); $m = date("n",strtotime($ym.$lastmonth)); $ly = date('Y',strtotime($ym.$lastmonth)); echo'<head>'.$ly."年".$m."月".'</head>'; としたときは受け取れるのですが 上記部分を含めた部分をhelperに移そうとしたらundefinedになります。 因みにindex.blade.phpでは下記のようにしていて上手くいっていますがlast.bladeでも同じような作りにしたいと思っています。 (Index.blade.php)一部抜粋 @inject('our_helper',\App\Helpers\OurHelper::class) {{$our_helper->ourLogic($e_all)}} (OutHelper.php)一部抜粋 public function ourLogic($e_all) { $ym=Carbon::now(); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $youbi = array("日","月","火","水","木","金","土"); $countdate=date('t', mktime(0, 0, 0, $tm, 1, $ty)); foreach ($e_all as $e_time) { $e_all_by_day[$e_time->date_time][] = $e_time; } for ($i = 0; $i < $countdate; ++$i) { $d = mktime(0, 0, 0, $tm, 16 + $i, $ty); (達成したいこと) 当月を$ym,次月を$lastmonth,$mを月、$lyを年としてhelperに渡したいです。 (試みたこと) Helperを別に作ってLastHelperとしてlast.blade.phpからLastHelperとした。 @inject(‘last_helper',\App\Helpers\LastHelper::class) {{$last_helper->LatLogic($e_all)}} public function lastLogic($e_all) { $dt=Carbon::now(); $ym=$dt->format('Ym'); $lastmonth = date("Ym",strtotime($ym."01"." -1 month ")); $nextmonth = date("Ym",strtotime($ym."01"." +1 month ")); $m = date("n",strtotime($ym.$lastmonth)); $ly = date('Y',strtotime($ym.$lastmonth)); (結果) ymとmがundefinedとなります。 何度もすみませんがご教授の程よろしくお願い致します。

    • ベストアンサー
    • PHP
  • php からlaravelで作り直した場合

    a hrefの書き方がわかりません。 index.phpからa hrefでlast.phpに 先月遷移をさせるソースは下記で動きます。 それをindex.blade.phpからlast.blade.phpに遷移させる ことができません。 一応、web.phpとcontrollerを次のように準備しました。 controllerはDBと繋げているので登録してあるデータを取ってきて last.blade.phpに渡すようにしています。 (index.php)動きます <?php $ym = date("Ym"); $lastmonth = date("Ym",strtotime($ym."01"." -1 month ")); $nextmonth = date("Ym",strtotime($ym."01"." +1 month ")); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 echo '<a href="last.blade.php?ym='.$lastmonth.'"><< 先月</a>'; echo'<head>'.$ty."年".$tm."月".'</head>'; $this_month_days = date("t",strtotime($ym."01"));//当月の日数を取得 ?> (last.php) 最初の部分だけ記載 $ym = (isset($_GET["ym"]))? $_GET["ym"] : date("Ym"); 以下からlaravelで作り直しを試みた記載 (index.blade.php)動かないindex.phpのa hrefの部分のみ下記の通り変更 syntax error, unexpected 'user' (T_STRING), expecting ';' or ','エラーが出る。 echo '<a href="{{route('user.local',['ym'=>'$lastmonth'])}}"><< 先月</a>'; (web.php)last部分だけ抜粋 userフォルダの下にlast.blade.php,index.blade.phpがある Route::get('/last', [KintaiController::class,'last']) ->middleware('auth:users') ->name('last'); (controller)KintaiControlerという名前でcontrollerを作ってある一部抜粋   public function last($lastmonth) { // $e_all = Melon::select('price_a','price_b','price_c','price_d')->paginate(3); $e_all = Kintai::all(); return view('user.last',compact('e_all')); } よろしくお願いします。

    • 締切済み
    • PHP
  • DB(mysql)のデータをviewに反映

    以前に投稿して回答を頂いた物に少し手を加えました。 前回は、入力した値を直接htmlファイルに表示させる仕様にしていましたが今回は一旦、DB側に登録して同じ日付のデータを全件表示させるという仕様に変えました。DB(mysql)側に登録しデータを取ってくるのは出来たのですが一件のみの取得表示になります。出来れば入力ずみの同じ日付けのデータを全件取得しデータが入っている所だけ表示したいのですが下記のソースでは、最新のデータしか表示されません。文字数の関係上、開始時間だけ取るようなソースコード記載しています。 (補足)laravelを使用 foreach($e_all as $e_time); $e_allで順に入ったデータを$e_timeに入れて $e_time->kubun $e_time->start_timeなどで順に取得させています。 (ソース一部抜粋) <table> <tr> <th>日付</th> <th>曜日</th> <th >区分</th> <th >開始</th> <th >終了</th> <th >休憩</th> <body> <?php $youbi = ['日', '月', '火', '水', '木', '金', '土']; $countdate = date('t', mktime(0, 0, 0, 10, 1, 2021)); for ($i = 0; $i < $countdate; ++$i) { $d = mktime(0, 0, 0, 10, 16 + $i, 2021); foreach($e_all as $e_time); echo '<tr>'; echo '<td class="px-4 py-3">'.date('d', $d).'</td>'; echo '<td class="px-4 py-3">'.$youbi[date("w",$d)].'</td>'; if(date('Y-m-d', $d) == $e_time->date_time){ if(!empty($e_time->start_time)){ echo '<td class="px-4 py-3">'.$e_time->kubun.'</td>'; echo '<td class="px-4 py-3">'.$e_time->start_time.'</td>'; }else{ echo '<td></td>'; } } echo '</tr>'; } ?> </body> </table> (イメージ) 16 火  17 水  DB側に同じ日付にデータがあれば全件取得表示をさせたい

    • ベストアンサー
    • PHP
  • 送信したデータが受け取れない(php)

    Laravelで日つけをテーブルで表示してその日つけの横の ボタンを押すと次の画面に遷移するようなことをやろうとしています。 受信側で受け取った日つけを一旦そのままで表示して 編集しようとしています。 ページ遷移はしますが、受信側のinput typeのvalue値で表示させようと したところ値が表示されません。特にエラーにはなりません。 因みに日付は表示側でループしていて172431(2022年の7月の日曜日) を試しに送信側で echo を掛けたら表示されます。 また、遷移するときのurlにはhttp://localhost:8000/exchange/17と出て Exchangeページはちゃんと遷移できているのでデータがきちんと渡っていないようです。よろしくおねがいします。 (送信側) echo '<form action="'.url('exchange/'.$dddd). '" method="POST">'; echo '<input type="hidden" name="_token" value="' . csrf_token() . '">'; echo '<input type="hidden" name="date_time" value="$dddd">'; echo '<input type="hidden" name="start_time" value="00:00">'; echo "<button type=\"submit\" class=\"btn btn-primary\">編集編集</button>"; (受取側) <input type="date" id="date-time" name="date_time" value=<?php print $_POST["date_time"]?> class="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 focus:border-indigo-500 focus:bg-white focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"> (Controller) Route::post('/exchange/{dddd}', [KintaiController::class,'exchange']) ->middleware('auth:users') ->name('exchange'); (日付を計算) $ym = date("Ym"); $d = mktime(0, 0, 0, $ym, 16 + $i, $ym); //日付ごとの配列のキー $dd = date('Y-m-d', $d);//2022-7-27 $dddd = date('d',strtotime($dd)); echo $dddd;//1724310714

    • 締切済み
    • PHP
  • strtotimeについて

    指定された月の翌月を返したく以下のようにしました。 // 200909の場合翌月の200910を返す。これは問題ありません echo date('Ym', strtotime('+1 month')); // 問題は以下から // 指定の月をセット $str = '200910; // どちらの場合も200910を返す echo date($str, strtotime('+1 month')); echo date($str, strtotime('-1 month')); このような方法で$strが200911であれば200912を返し200912であれば201001を返したのですが どのようにすれば可能でしょうか?

    • 締切済み
    • PHP
  • コンストラクタを2ケ書いたらエラーになりました

    前回質問をさせて戴いたように、helperの計算部分を切り出しをして serivceを作りました。(ZangyoService) データベースから取得したデータの計算部分と結果判定表示部分を helperとserviceに分けました。 残業計算部分をserivice側で計算させてhelperに戻す処理は出来ました。 合わせて祝日判定を別のサービスに切り出すべくOurHelperにてHolidayServiceを 呼び出す処理を書いたところ、constructは2個かけないとエラ〜が出ました。 OurHelperの中にZangyoServiceとHolidayServiceを呼び込んでそれぞれの Serviceで計算と判定させてHelperに表示させたいと思っています。 また別の方法としてhelperとserviceを2ケづつ(OurHelperとZangyoService,SyuHelperとHolidayService)用意してそれぞれをindex.blade.phpに読み込ませようと しましたがtableとtrをourhelperに記載してループさせているために 行が揃いません。 表示イメージは下記のようなものをイメージしています。 日付 曜日 区分  開始  終了 休憩  実働  残業 深夜残業  祝日 11/23 水  3 9:00 18:00 1:00 8:00 0:00 0:00 勤労感謝の日 12/9  金  5  9:00 23:00 1:00 13:00 1:00 1:00 12/10 土  3  9:00 23:00 1:00 13:00 12:00 1:00 12/11 日  4  9:00 23:00 1:00 13:00 0:00 0:00 また別の質問になるのですが、日付ループをhelperとserviceどちらにも 同じように書いていますが、どちらか一方にループの部分を書いて判定させれないでしょうか? helperのソースを一部抜粋 use App\Services\ZangyoService; use App\Services\HolidayService; use App\Models\User; use App\Models\Kintai; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use \SplFileObject; class OurHelper { private $holiday; private $zan; private $zangyoService; private $holidays = []; private $holidayService; public function __construct(ZangyoService $zangyoService) { $this->zan = $zangyoService; } public function __construct(HolidayService $holidayService) { $this->holiday = $holidayService; } public function ourLogic($e_all){ $ym=Carbon::now(); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $youbi = array("日","月","火","水","木","金","土"); $countdate=date('t', mktime(0, 0, 0, $tm, 1, $ty)); foreach ($e_all as $e_time) { $e_all_by_day[$e_time->date_time][] = $e_time; } for ($i = 0; $i < $countdate; ++$i) { $ym=Carbon::now(); $tm = date("n",strtotime($ym));//月 $ty = date("Y",strtotime($ym));//年 $youbi = array("日","月","火","水","木","金","土"); $countdate=date('t', mktime(0, 0, 0, $tm, 1, $ty)); foreach ($e_all as $e_time) { $e_all_by_day[$e_time->date_time][] = $e_time; } for ($i = 0; $i < $countdate; ++$i) { echo '<tr>'; どうかよろしくお願い致します。

    • ベストアンサー
    • PHP
  • 編集ボタン

    laravelで編集ボタンを作成しようとしていますがエラーになります。 エラーメッセージは'か;が足りないと言っているようです。 因みにエラーがでるコードは echo '<td><a href="{{route('user.create',['id'=>$e_time->id])}}" class="btn btn-info">'編集'</a></td>'; 下記のコードではエラーは出ません。 echo '<td class="border border-gray-400 ..." align="center"><input type="submit" value="編集"></td>'; よろしくお願いします。

    • ベストアンサー
    • PHP
  • 変数で来た指定日に対して、+3ヶ月、+6ヶ月、+12ヶ月を計算する方法

    変数で来た指定日に対して、+3ヶ月、+6ヶ月、+12ヶ月を計算する方法が知りたいです。 こんな感じで、当日に対して+する事は知っているのですが echo "1週間後 = " . date("Y/m/d",strtotime("+1 week")); echo "1ヶ月後 = " . date("Y/m/d",strtotime("+1 month")); echo "1年後  = " . date("Y/m/d",strtotime("+1 year")); 当日ではなく、変数できた指定の年月日に対して足す方法が解らなくて困っています。 $data03 = "2010-10-01"; //$data04 = strtotime("+3 month",$data03); $data04 = strtotime($data03,"+3 month"); //$data04 = $data03 + strtotime("+3 month"); echo '3ヶ月後:'.$data04.'<br />'; 結果 3ヶ月後:1285858800 strtotime関数のマニュアルは見ましたが良くわかりません… まったく違う方法でも良いのでお願いします。 いろいろ検索しましたが、当日からの計算方法しか見付かりませんでした。 宜しくお願い致します。

    • ベストアンサー
    • PHP