LoginSignup
6
6

More than 5 years have passed since last update.

Laravel Collective の annotations を導入しよう

Last updated at Posted at 2017-07-13

Laravel Collective を導入して,アノテーションでルーティングを実現し,動作確認まで行います。
使用した Laravel のバージョンは 5.4 です。

プロジェクトを作成

ここでは仮に mycollectiveproject という名前のプロジェクトを作成します。

$ composer create-project laravel/laravel mycollectiveproject

Laravel Collective をインストール

$ cd mycollectiveproject
$ composer require laravelcollective/annotations

サービスプロバイダーを作成

内容は, Laravel Collective の公式サイトからコピーしたものに手を加えたものです。

app/Providers/AnnotationsServiceProvider.php
<?php

namespace App\Providers;

use Collective\Annotations\AnnotationsServiceProvider as ServiceProvider;

class AnnotationsServiceProvider extends ServiceProvider {

    /**
     * The classes to scan for event annotations.
     *
     * @var array
     */
    protected $scanEvents = [];

    /**
     * The classes to scan for route annotations.
     *
     * @var array
     */
    protected $scanRoutes = [];

    /**
     * The classes to scan for model annotations.
     *
     * @var array
     */
    protected $scanModels = [];

    /**
     * Determines if we will auto-scan in the local environment.
     *
     * @var bool
     */
    protected $scanWhenLocal = true;

    /**
     * Determines whether or not to automatically scan the controllers
     * directory (App\Http\Controllers) for routes
     *
     * @var bool
     */
    protected $scanControllers = true;

    /**
     * Determines whether or not to automatically scan all namespaced
     * classes for event, route, and model annotations.
     *
     * @var bool
     */
    protected $scanEverything = true;
}

サービスプロバイダーを登録

config/app.php にサービスプロバイダーを登録します。

config/app.php
  // (長いので省略)
  'providers' => [
    // (長いので省略)
    App\Providers\AnnotationsServiceProvider::class
    // (長いので省略)
  ];
  // (長いので省略)

コントローラーを作成

$ php artisan make:controller HomeController
app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller {
  /**
   * @Get("/home", as="index")
   */
  public function index()
  {
    return view('welcome');
  }
}

内蔵サーバーを起動して確認

$ php artisan serve

ブラウザーを起動して表示

http://localhost:8000/ で表示された画面と,http://localhost:8000/home で表示された画面が同じであれば成功です。

これが何の役にたつのか

ルーティングの設定を,一つのファイルで管理するのではなく,各コントローラーに設定することで,コンフリクトを回避することができます。

ルーティングの設定は routes/web.php 等 (以前はroutes.php) に行いますが,ファイルが一つのため,複数人で開発を行っていると,svn や git の管理上コンフリクトが発生しやすいという問題が発生します。

コントローラーは担当者一人が編集することが多いと思うので,ルーティングの設定を各コントローラーに書くことで,コンフリクトを発生しにくくして,この問題を解決できます。

Java + Spring MVC なんかではおなじみのソリューションですね^^

参考

6
6
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
6
6