初めに
PHPでの開発時にはCakePHPフレームワークの機能でbakeコマンドによるソースの自動生成があります。
そのbakeコマンドを実行すると対話的に次々と入力を求められ、それに答えていくことでMVCモデルに沿ってのモデル/ビュー/コントローラのPHPプログラムを自動生成する機能になります。
コマンドのパラメータ内容によりテーブルの一覧・追加・削除・編集画面などのPHPプログラムが自動生成されるのです。
windowsならばコマンドプロンプトで,linuxならば端末で下記のようにデータベース情報を入力していきます。
詳しくは侍エンジニア塾のこちらの記事をみてください。
bakeコマンド
c:\workspace\sampleDB>C:\workspace\cakephp\app\Console\cake bake project Welcome to CakePHP v2.5.9 Console --------------------------------------------------------------- App : sampleDB Path: c:\workspace\sampleDB\ --------------------------------------------------------------- What is the path to the project you want to bake? [c:\workspace\sampleDB\myapp] > Skel Directory: C:\workspace\cakephp\lib\Cake\Console\Templates\skel Will be copied to: c:\workspace\sampleDB\myapp --------------------------------------------------------------- Look okay? (y/n/q) [y] > --------------------------------------------------------------- Created: myapp in c:\workspace\sampleDB\myapp --------------------------------------------------------------- * Random hash key created for 'Security.salt' * Random seed created for 'Security.cipherSeed' * Cache prefix set * app/Console/cake.php path set. CakePHP is on your `include_path`. CAKE_CORE_INCLUDE_PATH will be set, but comme nted out. * CAKE_CORE_INCLUDE_PATH set to C:\workspace\cakephp\lib in webroot/index.php * CAKE_CORE_INCLUDE_PATH set to C:\workspace\cakephp\lib in webroot/test.php Project baked successfully! c:\workspace\sampleDB>
フォルダー構成
各フォルダー構成は決められております。
基本的にはモデル/コントローラ/ビューは各フォルダーへ格納しないといけません。
”SyouhinMastersXXXX.php” は例題として作成いたしましたので読み替えてください。
※SyouhinMastersはテーブル名となります。
生成ソース
モデル(SyouhinMasters.php)
<?php
App::uses('AppModel', 'Model');
/**
* SyouhinMaster Model
*
*/
class SyouhinMaster extends AppModel {
/**
* Display field
*
* @var string
*/
public $displayField = 'name';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'name' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'price' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'create_dt' => array(
'datetime' => array(
'rule' => array('datetime'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
}
コントローラ(SyouhinMastersController.php)
<?php
App::uses('AppController', 'Controller');
/**
* SyouhinMasters Controller
*
* @property SyouhinMaster $SyouhinMaster
* @property PaginatorComponent $Paginator
*/
class SyouhinMastersController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
/**
* index method
*
* @return void
*/
public function index() {
$this->SyouhinMaster->recursive = 0;
$this->set('syouhinMasters', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->SyouhinMaster->exists($id)) {
throw new NotFoundException(__('Invalid syouhin master'));
}
$options = array('conditions' => array('SyouhinMaster.' . $this->SyouhinMaster->primaryKey => $id));
$this->set('syouhinMaster', $this->SyouhinMaster->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->SyouhinMaster->create();
if ($this->SyouhinMaster->save($this->request->data)) {
$this->Session->setFlash(__('The syouhin master has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The syouhin master could not be saved. Please, try again.'));
}
}
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->SyouhinMaster->exists($id)) {
throw new NotFoundException(__('Invalid syouhin master'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->SyouhinMaster->save($this->request->data)) {
$this->Session->setFlash(__('The syouhin master has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The syouhin master could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('SyouhinMaster.' . $this->SyouhinMaster->primaryKey => $id));
$this->request->data = $this->SyouhinMaster->find('first', $options);
}
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->SyouhinMaster->id = $id;
if (!$this->SyouhinMaster->exists()) {
throw new NotFoundException(__('Invalid syouhin master'));
}
$this->request->allowMethod('post', 'delete');
if ($this->SyouhinMaster->delete()) {
$this->Session->setFlash(__('The syouhin master has been deleted.'));
} else {
$this->Session->setFlash(__('The syouhin master could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
}
ビューテンプレート(View/SyouhinMasters/view.ctp)
<div class="syouhinMasters view">
<h2><?php echo __('Syouhin Master'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($syouhinMaster['SyouhinMaster']['id']); ?>
</dd>
<dt><?php echo __('Name'); ?></dt>
<dd>
<?php echo h($syouhinMaster['SyouhinMaster']['name']); ?>
</dd>
<dt><?php echo __('Price'); ?></dt>
<dd>
<?php echo h($syouhinMaster['SyouhinMaster']['price']); ?>
</dd>
<dt><?php echo __('Create Dt'); ?></dt>
<dd>
<?php echo h($syouhinMaster['SyouhinMaster']['create_dt']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Syouhin Master'), array('action' => 'edit', $syouhinMaster['SyouhinMaster']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Syouhin Master'), array('action' => 'delete', $syouhinMaster['SyouhinMaster']['id']), array(), __('Are you sure you want to delete # %s?', $syouhinMaster['SyouhinMaster']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Syouhin Masters'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Syouhin Master'), array('action' => 'add')); ?> </li>
</ul>
</div>
ほかにも、登録(add.ctp),編集(edit.ctp)があります。上記は一覧画面です。
動作結果
気を付けていただきたいのはURLです。下記URLで起動しますが、SyouhinMastersはコントローラを呼んでおります。SyouhinMastersController.php のController.phpの左側で起動できることを思えておいてください。
URL → http://localhost/cakePhpBakeSample/SyouhinMasters



まとめ
CakePHPは日本では最も多くのWebアプリケーションに導入されているPHPフレームワークです。
O/Rマッピング(ActiveRecordパターン)やscaffolding機能やbakeコマンドより初心者でも敷居が低く、生産性が高いフレームワークなのですがオブジェクト指向を取り入れれてない点が残念です。
今後はFuelPHPやLarabelでの説明ができればと思っております。

