CakePHP3でコンポーネントを作成する
開発環境は、Windows 7 Professional(32bit)+XAMPP v3.22+CakePHP 3.6.4。
複数のコントローラで使う共通処理をまとめたものをコンポーネントと言います。今回は、その作り方をメモしておきます。
1.カレントディレクトリをコンポーネントを作るディレクトリにして、
bin\cake bake component Common
と入力する。src/Controller/ComponentにCommonComponent.phpが作成されている。
2.CommonComponent.phpを実行して、クラスの中に、以下の関数を作ってみる。
<?php public function add($number1, $number2){ return $number1 + $number2; } ?>
3.使用するコントローラで、作ったコンポーネントを読み込む。試しに、SamplesController.phpにCommonコンポーネントを読み込む。
<?php /* initalize()メソッドを追加する */ public function initialize(){ parent::initialize(); $this->loadComponent('Common'); } /* indexアクションに追加する */ public function index(){ $result = $this->Common->add(10,20); $this->set("result",$result); } ?>
4.テンプレートをsrc/Template/Samples/index.ctpに作る。
<?= $result ?>
実行結果
■現在読み込んでいるコントローラー名を取得する
1.上記のファイルを修正して作ってみることにします。CommonComponentに以下の関数を追加します。
<?php public function c_name(){ return $this->_registry->getController()->name; } ?>
2.SamplesController.phpのindexアクションを書き換えます。
<?php public function index(){ $result = $this->Common->c_name(); $this->set("result",$result); } ?>
実行結果