LoginSignup
18
25

More than 5 years have passed since last update.

モデルでデフォルトモデル以外を使う方法

Last updated at Posted at 2014-02-26

App:usesとApp::importとClassRegistry::init();がある。

使い方

import
App::import('Model','KeiyakuList');
$KeiyakuList = new KeiyakuList;

$res = $KeiyakuList->find('all');
uses
App::uses('KeiyakuList','Model');
$KeiyakuList = new KeiyakuList;

$res = $KeiyakuList->find('all');

App:usesとApp::importは引数が逆なので注意!

ClassRegistry
$KeiyakuList = ClassRegistry::init('KeiyakuList');

$res = $KeiyakuList->find('all');

どれ使うか?

何が適するかは人それぞれだと思う。

ちなみに自分は、モデルが規約通りなのと、遅延ロードでパフォーマンスが優れているのでApp::usesを使っている。

また、ClassRegistryはインスタンスが生成済みであれば、生成済みのインスタンスを返す。いわゆるGoFのシングルトン形式でインスタンスを生成している。なので違う性質のインスタンスをいくつか作る場合は適していない。

インスタンス生成用のメソッドを作る

AppModelあたりに生成用の関数を作る。
パラメータのモデル名を受けて、importしてnewして、プロパティに設定する。
一工夫でarrayのキャストを使って、パラメータが文字列でも配列でもいいようにしている。

AppModel
public function loadModel($model_list) {
  foreach((array)$model_list as $model){
    App::uses($model,'Model');
    $this->{$model} = new $model();      
  }
}

各モデルのメソッドからはこんな感じで使う。

各モデル
//生成するモデルがひとつの場合
$this->loadModel('Foo');
$this->Foo->find('all');

//生成するモデルが複数の場合
$this->loadModel(['Foo','Bar']);
$this->Foo->find('all');
$this->Bar->find('all');

参考:[cakePHP]Model内で利用できるloadModelの実装

18
25
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
18
25