Cake風にコンポーネントを使う
CakePHPの場合、コントローラで
<?php class HogeController extends AppController { var $components = array('Session'); function index() { $this->Session->read('login'); } }
みたいな感じでコンポーネントを使うことができた。
これはちょっと便利だったのでAkelosでも使えるようにする。
app/application_controller.php
<?php class ApplicationController extends AkActionController { var $components = ''; function __construct() { $this->beforeFilter(array( 'loadComponents' )); } function loadComponents() { $components = Ak::stringToArray($this->components); $components_dir = AK_BASE_DIR.DS.'app'.DS.'controllers'.DS.'components'; foreach($components as $component) { if(!isset($this->{$component})) { include_once($components_dir.DS.AkInflector::underscore($component).'.php'); $class = $component.'Component'; $this->{$component} = new $class(&$this); } } } } ?>
使用したいコンポーネントは以下のように作成する。
app/controllers/components/hoge.php
<?php class HogeComponent extends AkObject { var $controller = null , $hoge = 0 , $fuga = 0; function __construct(& $controller) { $this->controller =& $controller; } } ?>
実際にコンポーネントを利用する場合は、コントローラで「var $components = 'コンポーネント名1,コンポーネント名2,...';」という感じで使えるようになる。※コンポーネント名はunderscoreで。
<?php class SampleController extends ApplicationController { var $components = 'hoge'; function index() { // HogeComponentには$this->Hogeでアクセスできる。 $this->Hoge->hoge = 1; $this->Hoge->fuga = 1; } } ?>
ログインユーザ情報とかアクセス権の操作とかはコンポーネントでやらせたいのでこれが使えると割と便利。