作り方
Componentの生成
プロジェクトのbinフォルダに移動し、以下のコマンドを実行。
cake bake component コンポーネント名
ここで、cake bake component TestComponentのように、Componentという単語を含めると精製されるファイルがTestComponentComponentとなってしまうので、cake bake component TestのようにComponentの前の部分だけを指定する。
初期処理
Componentが生成される時に、initializeメソッドが呼ばれる。
initializeメソッドは配列1つを引数に取る(Component読み込み時の引数が入る)。
class TestComponent extends Component{
public function initialize(array $config) {
/*初期処理*/
}
}
テーブルの読み込み
DBを扱うためには、テーブルの読み込みが必要となるが、コントローラのようにloadModelを使って読み込むことができない。
そのため、TableRegistry::getを使う。
TableRegistry::getはモデル名を入れると、テーブルオブジェクトが得られる。
loadModelを使ったときと同じように使いたいなら、$this->モデル名のフィールドに格納しておくといい。
public function initialize(array $config) {
$this->Test = TableRegistry::get("TestModel");
}
public function test() {
$this->Test
->find()
->all();
}
コントローラを扱う
Componentの中で呼び出し元のコントローラを参照することもできる。
$this->_registry->getController()でコントローラが取得できる。
これを使うと、テーブルの読み込みなどもloadModelで扱うこともできる。
public function initialize(array $config) {
$this->controler = $this->_registry->getController();
}
public function test() {
$this->controller->loadModel("TestModel");
$this->controller
->TestModel
->find()
->all();
}
ただし、これだとコントローラに処理が依存してしまうため、Shellで使うことができないので、非推奨。
使い方
CakePhp3のComponentの使い方まとめを参照。
自作のコンポーネントも既存のコンポーネントと同じように読み込み、使うことができる。