未経験エンジニアが知っておくべき事(初心者向け)php/laravel


はじめに

エンジニア未経験に陥りやすいのがソースの追い方がわからなくなりますよね
バグ改修、DB保存などの実装は
View → Controller → Model → DB
だけの話であって、本当に!シンプルに!単純に!これだけの話なんです。

そこでServiceやらRepositoryとかが入ってくるから余計にわからなくなってくると思うんですが、
こういった概念はあくまでもコードの可読性をあげる為のものであって、MVCに則る実装において基本形は変わらないのです。
経験者がその実装はrepositoryに書いてね。ってあたかも当然だよね?みたいな雰囲気を醸し出す為、???みたいな状況になっていくと思います
例として、LaravelにおいてデータをviewからDB登録するまでの流れを書いていきますね

Routing

ディレクトリ:/routes/web.php
それぞれの橋渡しの役目でindexを入れるとurlにlocalhost/notificationと叩くとcontrollerが走るよーって意味となる
いわゆるView → Controller → Model → DBの「→」の役目
※resourceとはcrud機能を一挙される(resourceがわからない場合、get/postにしてくださいね)

Route::resource('notification', 'NotificationController');

View

ディレクトリ:/resources/views
viewにて、送信する画面を作成します。Laravel想定なのでviewはbladeで書いています。
※classはBootstrapを使用しています。
※ソースはindex.blade.phpのみ

<div class=“col-md-8 col-md-offset-2”>
    {{Form::open([‘url’=>‘/notification’,‘method’=>‘post’,‘files’=>‘true’])}}
    <section class=“content”>
        <table class=“table table-bordered”>
            <tr>
                <th>{{Form::label(‘title’,‘タイトル’)}}</th>
                <td>{{Form::text(‘title’,‘’,[‘placeholder’=>‘タイトル’])}}</td>
            </tr>
            <tr>
                <th>{{Form::label(‘body’,‘内容’)}}</th>
                <td>{{Form::textarea(‘body’,‘’,[‘placeholder’=>‘内容を入力してください‘])}}</td>
            </tr>
        </table>
    </section>
    <section class=“content”>
        {{ Form::submit(‘作成’,[“class”=>“btn btn-primary”]) }}
    </section>
    {{ Form::close() }}
</div>

Model

ディレクトリ:/app/Models/Notification.php
modelは雑な説明ですが、table=modelと思ってください。
controllerからmodelを呼び込むということは、controllerからtableを呼び込むと同一です。
storeの場合、contollerからmodelを呼び出し、作成する流れとなります。

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Notification
 * @package App\Models
 */
class Notification extends Model
{

    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = [
        'filtering',
        'title',
        'body'
    ];
}

Controller

ディレクトリ:/app/Http/Controllers/NotificationController.php
urlを叩いたら、まずcontrollerのindexが呼び出され、表示させます。
表示の流れは、controller→viewです。
一番最初に書いた流れはDB保存(store)となります。

    /**
     * お知らせ一覧
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $notifications = Notification::all();

        return view('admin.notification.index')
            ->with('notifications',$notifications);
    }
    /**
     * お知らせ追加画面
     * @return View
     */
    public function create()
    {
        return view('notification.create');
    }
    /**
     * お知らせ追加
     * @param Notification $notification
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        Notification::create($data);

        return redirect('/notification')->with('flash_success', 'お知らせを作成しました');
    }
    /**
     * お知らせ編集画面
     * @param Request $notification
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Notification $notification)
    {
        return view('admin.notification.edit')
                ->with('notification',$notification);
    }
    /**
     * お知らせ更新
     * @param Request $notification
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function update(Request $request,Notification $notification)
    {
        $notification->title = $request->title;
        $notification->body  = $request->body;
        $notification->save();

        return redirect('/notification')->with('flash_success', 'お知らせを更新しました');
    }
    /**
     * お知らせ削除
     * @param  Notification $notification
     * @return \Illuminate\Http\Response
     */
    public function destroy(Notification $notification)
    {
        $notification->delete();
        return redirect('/admin/notification')->with('flash_success', 'お知らせを削除しました');
    }

余談

View → Controller → Model → DBの流れをズババーーっと書いたのですが、スクールとかで学んで現場で実装をするとき、全然書いている内容が違う、、となってしまうことがあると思います。
それが何故かというと先ほど言ったRepository概念とかが入ってくるからです。
controllerはあくまでもviewとmodelを呼び出す、呼び出される概念なだけで、DBを直接、、となると少し変わってくるのです。その為にrepositoryにmodelを呼び出す実装を書いたりするケースがあります。

repositoryを使用する場合
View → Controller ←→ Contract ←→ Repository → Model → DB

ただ、これも一概ではなくService概念を取り入れるところもあれば、controllerに全てかくところもあります(実際にcontrollerに1万行とかありました。。)
何故違うディレクトリに書くことが良いとされるかというと、単純に可読性を高めようぜ!!ってところですが、最初に申した通り、基本形は変わりません。なので、controllerから何を呼び出しているのかを見つけるところが鍵になると思います。