Laravel・PHP入門

PHPer初心者

【PHPUnit】【Laravel】定数ファイル管理

やりたいこと

  • 定数管理ファイルの場所変更
  • テストの時も定数管理

定数ファイルの場所を変更したい

今回の場合はbootstrap下へ作成したい。

bootstrap下でautoload.phpを作成する。

bootstrap/autoload.php

<?php

/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';

$filelist = glob(__DIR__ . '/constants/*.php');
foreach ($filelist as $file) {
    if (is_file($file)) {
        require_once $file;
    }
}
/*
|--------------------------------------------------------------------------
| Include The Compiled Class File
|--------------------------------------------------------------------------
|
| To dramatically increase your application's performance, you may use a
| compiled class file which contains all of the classes commonly used
| by a request. The Artisan "optimize" is used to create this file.
|
*/
$compiledPath = __DIR__.'/cache/compiled.php';
if (file_exists($compiledPath)) {
    require $compiledPath;
}
オートローダー呼び出し元ソース変更

通常はindex.phpでオートローダーを呼び出すのでこちらも変更
public/index.php

変更前:require __DIR__.'/../vendor/autoload.php';
変更後:require __DIR__.'/../bootstrap/autoload.php';
定数ファイルの作成

bootstrap下に早速作成する
定数なのでconstantsディレクトリを作成

bootstrap/constants/common.php

<?php
const FLAG_ON = 1;
const FLAG_OFF = 0;

フラグ作ってみました。

アプリケーションで使用

Post呼び出しの時に、表示するもの、しないものを分けてみます
例えばshow_flagカラムを追加し、flagがonの場合のみ表示したい

app/Repositories/Post.php

<?php
//  一部抜粋
    public function getAllPosts()
    {
        return $this->post_model
            ->where('show_flag', FLAG_ON) // ここで定数使用
            ->get();
    }

これでflagがonのpostのみがかえるようになりましたね

いざテスト

エラーが出る

./vendor/bin/phpunit tests/Feature/PostsTest.php

f:id:fresh_engineer:20180712230841p:plain

storage下のlogをみると、FLAG_ONなんて定数知らねーよ!!!!って
怒られます。。。

テストは指定している定数ファイルを読み込んでくれません。
なので読み込んでくれるようにベースのテストクラスで呼び出してあげます

ついでにベースのテストクラスも作る

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    public function setUp()
    {
        parent::setUp();
        $this->readConstants();
    }

    /**
     * テスト用に定数ファイル読み込み
     */
    private function readConstants()
    {
        $file_list = glob('./bootstrap/constants/*.php'); // 定数ファイルを全部取得
        foreach ($file_list as $file) {
            if (is_file($file)) {
                require_once $file; // 各ファイル1度だけ読み込む
            }
        }
    }
}

こうして読み込んであげると、、、

./vendor/bin/phpunit tests/Feature/PostsTest.php


f:id:fresh_engineer:20180712231106p:plain

テスト通過!

これで定数も使いながらテストが実行できるようになりました。

以上