LoginSignup
8
11

More than 5 years have passed since last update.

FuelPHPのCoreクラス拡張

Last updated at Posted at 2016-09-08

たまにCoreクラス拡張するときに迷うのでメモ

手軽だからってcore下のクラスに直接処理を追加したり変更しないほうがいい
アップデートしたりローカル環境作りなおすとそこのコードが戻る
まずcore下をgit管理しないから履歴も分かりづらい

公式にやり方載ってます
http://fuelphp.jp/docs/1.8/general/extending_core.html

手順

  1. app/classes下に拡張したいクラスと同じ名前のファイルを作る
  2. 1.で作成したファイルに拡張したいクラスと同じクラス名のクラスを作り
    拡張したいCoreクラスを継承させる

  3. app/bootstrap.phpの\Autoloader::add_classesに
    'クラス名' => '1.で作ったファイルパス'
    のような形式で追加

※ 1.の作成場所はapp/classes下じゃなくていいかもしれない、modules毎に動作変えたいならmodules下の適切なとこに置くとか

詳しく

前提:
Feulのデバッグ情報を表示してくれるProfilerクラスにメソッドを追加したいとする

1 同じ名前のファイル作る

今回は全体でProfilerクラスを拡張したいので拡張クラスはapp/classes/override下に置く

profiler.phpを作成

2 Coreクラスの拡張

先ほど作ったファイルを編集

app/classes/override/profiler.php
/**
 * \Fuel\Core\Profiler を拡張
 */
class Profiler extends \Fuel\Core\Profiler
{

    /**
     * アクション毎の実行したクエリ情報を出力
     * debug_backtrace()だと情報が多すぎるから
     */
    public function getExecutedQueries(\Fuel\Core\Request $request)
    {
        if (static::$profiler) {
            static::$profiler->db = static::$profiler;
            static::$profiler->gatherQueryData();
            $queries = isset(static::$profiler->output['queries']) ? static::$profiler->output['queries'] : [];

            return static::formatForLog($queries, $request); // 自作 中身は割愛
        } else {

            return [];
        }
    }
}

これで拡張したい処理は追加した

3 bootstrap.phpに拡張したクラスを追加

app/bootstrap.phpを編集

app/bootstrap.php

// 前後の処理は変更しないので割愛

\Autoloader::add_classes([
    'Profiler' => APPPATH.'classes/override/profiler.php',
]);

これで拡張完了
後は作ったクラスが動作するか試してみる

※追加
もしmodules下に拡張クラスを置きたい場合はbootstrap.php\Autoloader::add_classesより前に
\Autoloader::add_core_namespace(指定したいネームスペース);
と記述し、
クラス名をProfilerだけではなく指定したいネームスペース\\Profilerとする

所感

久しぶりの投稿
はい、以上です。

8
11
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
8
11