25
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePhp3のComponentの作り方まとめ

Posted at

作り方

Componentの生成

プロジェクトのbinフォルダに移動し、以下のコマンドを実行。

cake bake component コンポーネント名

ここで、cake bake component TestComponentのように、Componentという単語を含めると精製されるファイルがTestComponentComponentとなってしまうので、cake bake component TestのようにComponentの前の部分だけを指定する。

初期処理

Componentが生成される時に、initializeメソッドが呼ばれる。
initializeメソッドは配列1つを引数に取る(Component読み込み時の引数が入る)。

TestComponent.php

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の使い方まとめを参照。
自作のコンポーネントも既存のコンポーネントと同じように読み込み、使うことができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?