たまにCoreクラス拡張するときに迷うのでメモ
手軽だからってcore下のクラスに直接処理を追加したり変更しないほうがいい
アップデートしたりローカル環境作りなおすとそこのコードが戻る
まずcore下をgit管理しないから履歴も分かりづらい
公式にやり方載ってます
http://fuelphp.jp/docs/1.8/general/extending_core.html
手順
- app/classes下に拡張したいクラスと同じ名前のファイルを作る
1.で作成したファイルに拡張したいクラスと同じクラス名のクラスを作り
拡張したいCoreクラスを継承させるapp/bootstrap.phpの\Autoloader::add_classesに
'クラス名' => '1.で作ったファイルパス'
のような形式で追加
※ 1.の作成場所はapp/classes下じゃなくていいかもしれない、modules毎に動作変えたいならmodules下の適切なとこに置くとか
詳しく
前提:
Feulのデバッグ情報を表示してくれるProfilerクラスにメソッドを追加したいとする
1 同じ名前のファイル作る
今回は全体でProfilerクラスを拡張したいので拡張クラスはapp/classes/override
下に置く
profiler.php
を作成
2 Coreクラスの拡張
先ほど作ったファイルを編集
/**
* \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
を編集
// 前後の処理は変更しないので割愛
\Autoloader::add_classes([
'Profiler' => APPPATH.'classes/override/profiler.php',
]);
これで拡張完了
後は作ったクラスが動作するか試してみる
※追加
もしmodules下に拡張クラスを置きたい場合はbootstrap.php
の\Autoloader::add_classes
より前に
\Autoloader::add_core_namespace(指定したいネームスペース);
と記述し、
クラス名をProfiler
だけではなく指定したいネームスペース\\Profiler
とする
所感
久しぶりの投稿
はい、以上です。