LoginSignup
10
9

More than 5 years have passed since last update.

viewからcontrollerを呼び出し

Posted at

Laravelをあつかっていると
単純にview側(blade)からControllerに戻れないかと思った。

自分の脳内イメージでは
route→Controller→view
の流れで、Controllerでデータを抜き出しviewで表示するイメージ

そのイメージで、view側からデータを取りなおせたらなと思うと、view側(blade)からControllerに戻れないかと言う話だ。

調べたところ
@injectというのが出てきた。

blade側での使い方は@extendsの様に書くけれど、後ろに二つ書くところがある。
1つ目はブレード内の変数の名前
2つ目はメソッドのあるクラスの場所
(ディレクトリーは[.]ではなく[/]で書く、最後の.phpは書かなくていい)
下記の例では、App\Servicesの層にMetricsService.phpを作っている
@sectionの中で呼び出すときは
{{1つ目に書いた変数->呼び出すメソッド()}}
で上手くいった。

blade.php
@extends('front.layout.base')
@inject('metrics','App\Services\MetricsService')
@section('content')
        monthly revenue: {{$metrics-> monthlyRevenue()}}.
@endsection
App\Services\MetricsService.php
<?php
namespace App\Services;
class MetricsService
{
    public function monthlyRevenue()
    {
        return 'hello method';
    }
}

laravelの解説では「サービス注入」というそうです

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9