More Related Content
Similar to CakePHP+Smartyハイブリッドによるラクラク開発 (20)
CakePHP+Smartyハイブリッドによるラクラク開発
- 19. ソースコードは…
<?php else {
print("<?xml version="1.0" encoding="UTF-8" ?>n"); ?>
$odTotalFloor = $_POST['odTotalFloor']; <p><?php print($count) ?>件ありました。</p>
?> <table border="1">
<!DOCTYPE html PUBLIC "- <thead>
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 <tr>
-transitional.dtd"> <th>注文コード</th>
<html xmlns="http://www.w3.org/1999/xhtml"> <th>注文日時</th>
<head> <th>注文合計金額</th>
<title>サンプル01: MVC未分離</title> <th>注文者氏名</th>
</head> <th>注文者住所</th>
<body> <th>注文者電話番号</th>
<h1>Histudy7 サンプル01: MVC未分離</h1> </tr>
<hr/> </thead>
<form action="sample01.php" method="post"> <tbody>
注文合計が <?php
<input type="text" name="odTotalFloor" value="<?php print($odTotalFloor) ?>"/>円 $sql2 = "SELECT * FROM orders WHERE od_total>=:od_total ORDER BY od_total";
以上の注文情報を<input type="submit" value="表示"/> $stmt2 = $db->prepare($sql2);
</form> $stmt2->bindParam(":od_total", $odTotalFloor);
<?php $stmt2->execute();
if(is_numeric($odTotalFloor)) { $i = 0;
$dsn = "mysql:host=localhost;dbname=histudy7"; while($row = $stmt2->fetch()) {
$username = "histudy"; ?>
$password = "hihi"; <tr>
<td><?php print($row['od_code']) ?></td>
try { <td><?php print(strftime('%Y/%m/%d %H:%M:%S',strtotime($row['od_date']))) ?
$db = new PDO($dsn, $username, $password); ></td>
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); <td><?php print($row['od_total']) ?></td>
$db->query("SET NAMES utf8;"); <td><?php print($row['od_name']) ?></td>
$sql1 = "SELECT COUNT(DISTINCT(od_code)) AS count FROM orders WHERE od <td><?php print($row['od_address']) ?></td>
_total>=:od_total ORDER BY od_total"; <td><?php print($row['od_tel']) ?></td>
$stmt1 = $db->prepare($sql1); </tr>
<?php
$stmt1->bindParam(":od_total", $odTotalFloor); }
$stmt1->execute(); ?>
$result1 = $stmt1->fetch(); </tbody>
</table>
$count = $result1["count"]; <?php
if($count == 0) { }
?> $db = null;
<p>表示すべき情報はありません。</p> }
<?php
}
- 22. さらに
<th>注文者住所</th>
<th>注文者電話番号</th>
</tr>
</thead>
<tbody>
<?php
$sql2 = "SELECT * FROM orders WHERE od_total>=:od_total ORDER BY od_total";
$stmt2 = $db->prepare($sql2);
$stmt2->bindParam(":od_total", $odTotalFloor);
$stmt2->execute();
$i = 0;
while($row = $stmt2->fetch()) {
SQL文!
ここに書いちゃうと、他のPHPファイルで使えない。
- 24. 表示画面 PHP 表示画面 PHP 表示画面
ここにも ここにも
$sql2 = "SELECT * FROM orders WHERE od_total>=:od_total ORDER BY od_total";
- 28. 表示画面 PHP 表示画面 PHP 表示画面
利用 利用
DB処理
PHP
Model
- 29. DB操作のクラス(DAO)を作る
<?php /**
require_once("OrderEntity.class.php"); * 指定金額以上の注文情報を取得するメソッド。
*
/** * @param integer $odTotalFloor 注文合計下限
* テーブルordersのデータ操作を行うDAOクラス。 * @return array 各要素はOrderEntityオブジェクト
* */
*/ public function findMoreThanOdTotalFloor($odTotalFloor) {
class OrderDAO { $orderEntities = array();
try {
/** $this->_db->query("SET NAMES utf8;");
* データソース $sql = "SELECT * FROM orders WHERE od_total>=:od_total ORDER BY
* od_total";
* @var PDO $stmt = $this->_db->prepare($sql);
*/
private $_db; $stmt->bindParam(":od_total", $odTotalFloor);
$result = $stmt->execute();
/** while($row = $stmt->fetch()) {
* コンストラクタ。データベースへの接続を行う。 $orderEntity = new OrderEntity();
* $odCode = $row['od_code'];
*/ $orderEntity->setOdCode($odCode);
public function __construct() { $orderEntity->setOdDate($row['od_date']);
$dsn = "mysql:host=localhost;dbname=histudy7"; $orderEntity->setOdTotal($row['od_total']);
$username = "histudy"; $orderEntity->setOdName($row['od_name']);
$password = "hihi"; $orderEntity->setOdAddress($row['od_address']);
$this->_db = new PDO($dsn, $username, $password); $orderEntity->setOdTel($row['od_tel']);
$this->_db- $orderEntities[$odCode] = $orderEntity;
>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }
} }
catch(PDOException $ex) {
/** $expMessage = "<p>DB接続に失敗しました。<hr/>";
* デストラクタ。データベースへの接続解除を行う。 $expMessage .= "例外の中身:Code=".$ex->getCode()."<br/>".$ex-
* >getFile()."(".$ex->getLine()."): ".$ex->getMessage()."<br/>".$ex-
*/ >getTraceAsString();
public function __destruct() { print($expMessage);
$this->_db = null; }
} return $orderEntities;
}
}
?>
- 30. 重要なところだけ見ると…
class OrderDAO {
~ 中略 ~
public function findMoreThanOdTotalFloor($odTotalFloor) {
$orderEntities = array();
try {
$this->_db->query("SET NAMES utf8;");
$sql = "SELECT * FROM orders WHERE od_total>=:od_total ORDER BY od_total";
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":od_total", $odTotalFloor);
$result = $stmt->execute();
while($row = $stmt->fetch()) { さっき出てきたSQL
$orderEntity = new OrderEntity();
文!
$odCode = $row['od_code'];
$orderEntity->setOdCode($odCode);
$orderEntity->setOdDate($row['od_date']);
$orderEntity->setOdTotal($row['od_total']);
$orderEntity->setOdName($row['od_name']);
$orderEntity->setOdAddress($row['od_address']);
$orderEntity->setOdTel($row['od_tel']);
$orderEntities[$odCode] = $orderEntity;
}
- 31. エンティティクラスを作る
<?php /**
* 注文者電話番号
/** * @var string
* 注文情報エンティティクラス。 */
* private $_odTel;
* @author Shinzo SAITO
* /**
*/ * @return integer 注文コード
class OrderEntity { */
/** public function getOdCode() {
* 注文コード return $this->_odCode;
* @var integer }
*/
private $_odCode; /**
* @param integer $odCode 注文コード
/** */
* 注文日時 public function setOdCode($odCode) { つまり、
*/ $this->_odCode = $odCode;
private $_odDate; } このクラス1コが
/** /** テーブルの1行分の
* 注文合計金額 * @return mixed 注文日時
* @var integer */ データに対応する
*/ public function getOdDate() {
private $_odTotal; return $this->_odDate;
}
/**
* 注文者氏名 ~ 以下setter/getterがつづく~
* @var string ?>
*/
private $_odName;
/**
* 注文者住所
* @var string
*/
private $_odAddress;
- 32. SQLの結果
od_code od_date od_total od_name od_address od_tel OrderEntity
4 2008/06/07 12:54:21 53500 中谷桃 … …
18 2008/06/07 12:54:21 53500 梶原淳 … …
OrderEntity
32 2008/06/07 12:54:21 53500 森俊之 … …
OrderEntity
連想配列に格
納
- 33. 表示画面 PHP 表示画面
利用
エンティティ
DB処理 (の連想配列)
PHP
- 34. Mが分離された処理PHPは…
<?php <section>
require_once("OrderEntity.class.php"); <?php if($count == 0) { ?>
require_once("OrderDAO.class.php"); <p>表示すべき情報はありません。</p>
<?php }
else { ?>
$orderEntities = array(); <?php print($count) ?>件ありました。
$odTotalFloor = $_POST['odTotalFloor']; <table border="1">
if(is_numeric($odTotalFloor)) { <thead>
$orderDAO = new OrderDAO(); <tr>
$orderEntities = $orderDAO->findMoreThanOdTotalFloor($odTotalFloor); <th>注文コード</th>
} <th>注文日時</th>
$count = count($orderEntities); <th>注文合計金額</th>
?> <th>注文者氏名</th>
<th>注文者住所</th>
<!DOCTYPE html> <th>注文者電話番号</th>
<html> </tr>
<head> </thead>
<meta charset="UTF-8"> <tbody>
<title>サンプル02: Mの分離</title> <?php foreach($orderEntities as $key1=>$orderEntity) { ?>
</head> <tr>
<body> <td><?php print($orderEntity->getOdCode()) ?></td>
<header> <td><?php print(strftime('%Y/%m/%d %H:%M:%S',strtotime($order
<h1>Histudy7 サンプル02: Mの分離</h1> Entity->getOdDate()))) ?></td>
</header> <td><?php print($orderEntity->getOdTotal()) ?></td>
<section> <td><?php print($orderEntity->getOdName()) ?></td>
<form action="sample02.php" method="post"> <td><?php print($orderEntity->getOdAddress()) ?></td>
注文合計が <td><?php print($orderEntity->getOdTel()) ?></td>
<input type="text" name="odTotalFloor" value="<?php print($odTotalFloor) ?> </tr>
"/>円以上の注文情報を<input type="submit" value="表示"/> <?php } ?>
</form> </tbody>
</section> </table>
<?php } ?>
</section>
</body>
</html>
- 38. 例えば、こんな画面のHTMLは…
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>サンプル03: Vの分離</title>
</head>
<body>
<header>
<h1>Histudy7 サンプル03: Vの分離</h1>
</header>
<section>
<table border="1">
<tr>
<th>注文コード</th>
<td>18</td>
</tr>
<tr>
<th>注文日時</th>
<td>2008/06/21 12:54:21</td>
</tr>
<tr>
<th>注文合計金額</th>
<td>53,500円</td>
</tr>
<tr>
<th>注文者氏名</th>
<td>梶原順</td>
</tr>
<tr>
<th>注文者住所</th>
<td>京都市伏見区小豆屋町</td>
</tr>
<tr>
<th>注文者電話番号</th>
<td>078-846-8767</td>
</tr>
</table>
</section>
</body>
</html>
- 40. DBデータによって変動する部分は…
<!DOCTYPE html> <tr>
<html> <th>注文者氏名</th>
<head> <td>梶原順</td>
<meta charset="UTF-8"> </tr>
<title>サンプル03: Vの分離</title> <tr>
</head> <th>注文者住所</th>
<body> <td>京都市伏見区小豆屋町</td>
<header> </tr>
<h1>Histudy7 サンプル03: Vの分離</h1> <tr>
</header> <th>注文者電話番号</th>
<section> <td>078-846-8767</td>
<table border="1"> </tr>
<tr> </table>
<th>注文コード</th> </section>
<td>18</td> </body>
</tr> </html>
<tr>
<th>注文日時</th>
<td>2008/06/21 12:54:21</td>
</tr> これら、変動する部分を変数化し
<tr>
<th>注文合計金額</th> て置き換え可能にしてみる
<td>53,500円</td>
</tr>
- 41. 変数化してみると…
<!DOCTYPE html> <tr>
<html> <th>注文者氏名</th>
<head> <td>#OD_NAME#</td>
<meta charset="UTF-8"> </tr>
<title>サンプル03: Vの分離</title> <tr>
</head> <th>注文者住所</th>
<body> <td>#OD_ADDRESS#</td>
<header> </tr>
<h1>Histudy7 サンプル03: Vの分離</h1> <tr>
</header> <th>注文者電話番号</th>
<section> <td>#OD_TEL#</td>
<table border="1"> </tr>
<tr> </table>
<th>注文コード</th> </section>
<td>#OD_CODE#</td> </body>
</tr> </html>
<tr>
<th>注文日時</th>
<td>#OD_DATE#</td>
</tr> このファイルを読み込んで使う
<tr>
<th>注文合計金額</th>
<td>#OD_TOTAL#円</td>
</tr>
- 42. Controller
表示画面 PHP 表示画面
読込
利用 +
変数置換
エンティティ
DB処理 (の連想配列) 変数化
PHP HTML
Model View
- 43. MVが分離されたControllerは…
<?php
require_once("OrderEntity.class.php");
require_once("OrderDAO.class.php");
$odCode = $_GET['odCode'];
Mからデータ取得
$orderDAO = new OrderDAO();
$orderEntity = $orderDAO->findyByPK($odCode);
Vファイルの読込
$htmlTemp = file_get_contents("sample03t.html");
$html = str_replace("#OD_CODE#", $orderEntity->getOdCode(), $htmlTemp);
$html = str_replace("#OD_DATE#",
strftime('%Y/%m/%d %H:%M:%S',strtotime($orderEntity->getOdDate())), $html);
$html = str_replace("#OD_TOTAL#", number_format($orderEntity->getOdTotal()), $html);
$html = str_replace("#OD_NAME#", $orderEntity->getOdName(), $html);
$html = str_replace("#OD_ADDRESS#", $orderEntity->getOdAddress(), $html);
$html = str_replace("#OD_TEL#", $orderEntity->getOdTel(), $html);
print($html);
Vファイルの変数置換
?>
- 47. HTMLは…
<!DOCTYPE html> <tr>
<html> <td>18</td>
<head> <td>2008/06/21 12:54:21</td>
<meta charset="UTF-8"> <td>53500</td>
<title>サンプル02: Mの分離</title> <td>梶原順</td>
</head> <td>京都市伏見区小豆屋町</td>
<body> <td>078-846-8767</td>
<header> </tr>
<h1>Histudy7 サンプル02: Mの分離</h1> <tr>
</header> <td>32</td>
<section> <td>2008/07/05 12:54:21</td>
<form action="sample02.php" method="post"> <td>53500</td>
注文合計が<input type="text" name="odTotalFloor" value="50000"/> <td>森俊之</td>
円以上の注文情報を<input type="submit" value="表示"/> <td>福岡県福岡市博多区</td>
</form> <td>078-846-8781</td>
</section> </tr>
<section> <tr>
11件ありました。 <td>1</td>
<table border="1"> <td>2008/06/04 12:54:21</td>
<thead> <td>56421</td>
<tr> <td>後藤武</td>
<th>注文コード</th> <td>兵庫県神戸市東灘区住吉町</td>
<th>注文日時</th> <td>078-846-8750</td>
<th>注文合計金額</th> </tr>
<th>注文者氏名</th> ~中略~
<th>注文者住所</th> </tbody>
<th>注文者電話番号</th> </table>
</tr> </section>
</thead> </body>
<tbody> </html>
<tr>
<td>4</td>
<td>2008/06/07 12:54:21</td>
<td>53500</td>
<td>中谷桃</td>
<td>和歌山県新宮市あけぼの</td> ル、ループ…
<td>078-846-8753</td>
</tr>
- 51. またまた、これを例にとると…
<table border="1">
<tr>
<th>注文コード</th>
<td>#OD_CODE#</td>
</tr>
<tr>
<th>注文日時</th>
<td>#OD_DATE#</td>
</tr>
<tr>
<th>注文合計金額</th>
<td>#OD_TOTAL#円</td>
変数が埋め込まれたtable </tr>
<tr>
タグの部分だけ見てみる <th>注文者氏名</th>
と <td>#OD_NAME#</td>
</tr>
<tr>
<th>注文者住所</th>
<td>#OD_ADDRESS#</td>
</tr>
<tr>
<th>注文者電話番号</th>
<td>#OD_TEL#</td>
</tr>
</table>
- 52. これがSmartyを使うと…
<table border="1">
<tr>
<th>注文コード</th>
<td>{$odCode}</td>
</tr>
<tr>
<th>注文日時</th>
<td>{$odDate|date_format:"%Y/%m/%d %H:%M:%S"}</td>
</tr>
<tr>
<th>注文合計金額</th>
<td>{$odTotal}円</td>
</tr>
<tr> {$変数名}
<th>注文者氏名</th>
<td>{$odName}</td> という記述
</tr>
<tr> ||
<th>注文者住所</th>
<td>{$odAddress}</td>
テンプレート変数
</tr>
<tr>
<th>注文者電話番号</th>
<td>{$odTel}</td>
</tr>
</table>
- 53. Controllerは…
<?php Smartyクラスの読
require_once("libs/Smarty.class.php"); 込
require_once("OrderEntity.class.php");
require_once("OrderDAO.class.php");
Smarty利用の準備
$oSmarty = new Smarty();
$oSmarty->template_dir = "./templates/";
$oSmarty->compile_dir = "./templates_c";
Mからデータ取得
$odCode = $_GET['odCode'];
$orderDAO = new OrderDAO(); テンプレートに送るデータを
$orderEntity = $orderDAO->findyByPK($odCode); セット
$oSmarty->assign("odCode", $orderEntity->getOdCode());
$oSmarty->assign("odDate", $orderEntity->getOdDate());
$oSmarty->assign("odTotal", number_format($orderEntity->getOdTotal()));
$oSmarty->assign("odName", $orderEntity->getOdName());
$oSmarty->assign("odAddress", $orderEntity->getOdAddress());
$oSmarty->assign("odTel", $orderEntity->getOdTel());
$oSmarty->display("sample01.tpl"); Vの表示
?>
- 59. テンプレートに送るデータの
セット
Smartyクラスのassignメソッドを使ってテンプレー
トに埋め込むデータをセット。
第1引数が変数名文字列、第2引数が値。
$oSmarty->assign("odCode", $orderEntity->getOdCode());
$oSmarty->assign("odDate", $orderEntity->getOdDate());
$oSmarty->assign("odTotal", number_format($orderEntity->getOdTotal()));
$oSmarty->assign("odName", $orderEntity->getOdName());
$oSmarty->assign("odAddress", $orderEntity->getOdAddress());
$oSmarty->assign("odTel", $orderEntity->getOdTel());
- 61. ところで…
<table border="1">
<tr>
<th>注文コード</th>
<td>{$odCode}</td>
</tr>
<tr>
<th>注文日時</th>
これ、
<td>{$odDate|date_format:"%Y/%m/%d %H:%M:%S"}</td>
</tr>
<tr>
<th>注文合計金額</th>
<td>{$odTotal}円</td>
</tr>
<tr>
<th>注文者氏名</th>
<td>{$odName}</td>
なに?
</tr>
<tr>
<th>注文者住所</th>
<td>{$odAddress}</td>
</tr>
<tr>
<th>注文者電話番号</th>
<td>{$odTel}</td>
</tr>
</table>
- 63. 修飾子の種類1
分類 修正子 説明
文字列操作 capitalize 単語の先頭を大文字に変換
lower 小文字に変換
upper 大文字に変換
cat 指定された変数を連結
replace 置き換え
regex_replace 正規表現による置換
書式設定 date_format 日付の書式設定
string_format 文字列の書式設定
default 初期値の設定
- 64. 修飾子の種類2
分類 修正子 説明
特殊文字処理 strip 空白・改行・タブの削除
strip_tags マークアップタグの削除
nl2br 改行文字を<br/>タグに置換
escape エスケープ処理
spacify 文字の間に空白挿入
文字列操作 truncate 指定桁で文字列を切り捨て
wordwrap 指定桁でワードラップ
indent インデント指定
- 65. 修飾子の種類3
分類 修正子 説明
文章情報 count_characters 文字数取得
count_paragraphs 段落数取得
count_sentences センテンス数取得
count_words 単語数取得
詳細は本家サイトのマニュアルを参照。
http://www.smarty.net/docs/ja/language.modifiers.tpl
- 70. テンプレートファイル(抜粋)は…
<section>
{if $count == 0}
<p>表示すべき情報はありません。</p> 分岐
{else}
{$count}件ありました。
<table border="1">
<thead>
<tr>
<th>注文コード</th>
<th>注文日時</th>
<th>注文合計金額</th>
<th>注文者氏名</th>
<th>注文者住所</th>
<th>注文者電話番号</th>
</tr>
ルー
</thead> プ
<tbody>
{foreach from=$orderEntities item="orderEntity"}
<tr>
<td>{$orderEntity->getOdCode()}</td>
<td>{$orderEntity->getOdDate()|date_format:"%Y/%m/%d %H:%M:%S"}</td>
<td>{$orderEntity->getOdTotal()|number_format}</td>
<td>{$orderEntity->getOdName()}</td>
<td>{$orderEntity->getOdAddress()}</td>
<td>{$orderEntity->getOdTel()}</td>
</tr>
{/foreach}
</tbody>
</table>
{/if}
</section>
- 72. ループ
ループの書式は
{foreach from=配列 item=各要素を格納する変数名}
~
{/foreach}
<tbody>
{foreach from=$orderEntities item="orderEntity"}
<tr>
<td>{$orderEntity->getOdCode()}</td>
<td>{$orderEntity->getOdDate()|date_format:"%Y/%m/%d %H:%M:%S"}</td>
<td>{$orderEntity->getOdTotal()|number_format}</td>
<td>{$orderEntity->getOdName()}</td>
<td>{$orderEntity->getOdAddress()}</td>
<td>{$orderEntity->getOdTel()}</td>
</tr>
{/foreach}
</tbody>
- 73. ループのelse
{foreach}~{foreachelse}~{/foreach}
でループがなかった時の表示が書ける。
<tbody>
{foreach from=$orderEntities item="orderEntity"}
<tr>
<td>{$orderEntity->getOdCode()}</td>
<td>{$orderEntity->getOdDate()|date_format:"%Y/%m/%d %H:%M:%S"}</td>
<td>{$orderEntity->getOdTotal()|number_format}</td>
<td>{$orderEntity->getOdName()}</td>
<td>{$orderEntity->getOdAddress()}</td>
<td>{$orderEntity->getOdTel()}</td>
</tr>
{foreachelse}
<tr>
<td colspan=“6”>表示するリストはありません。</td>
</tr>
{/foreach}
</tbody>
- 80. 例えば、以下のようなテーブル
orders
フィールド 種別 NOT NULL その他
od_code INTEGER YES 主キー / AUTO_INCREMENT
od_date DATETIME YES
od_total INTEGER YES
od_name TEXT YES
od_address TEXT YES
od_tel TEXT YES
members
フィールド 種別 NOT NULL その他
mb_code INTEGER YES 主キー / AUTO_INCREMENT
mb_name_last TEXT YES
mb_name_first TEXT YES
mb_mail TEXT YES
- 81. 主キーによる検索SQLは…
orders
$sql1 = "SELECT * FROM orders WHERE od_code=:od_code";
members
$sql2 = "SELECT * FROM members WHERE mb_code=:mb_code";
- 83. ModelクラスのfindByPKメソッドは…
<?php <?php
class OrderDAO { class MemberDAO {
public function findyByPK($odCode) { public function findyByPK($mbCode) {
$orderEntity = new OrderEntity(); $memberEntity = new MemberEntity();
try { try {
$this->_db->query("SET NAMES utf8;"); $this->_db->query("SET NAMES utf8;");
$sql = $sql =
"SELECT * FROM orders WHERE od_code=:od_code"; "SELECT * FROM members WHERE mb_code:mb_code";
$stmt = $this->_db->prepare($sql); $stmt = $this->_db->prepare($sql);
$stmt->bindParam(":od_code", $odCode); $stmt->bindParam(":mbCode", $mbCode);
$result = $stmt->execute(); $result = $stmt->execute();
while($row = $stmt->fetch()) { while($row = $stmt->fetch()) {
$orderEntity->setOdCode($row['od_code']); $memberEntity->setMbCode($row[„mb_code']);
$orderEntity->setOdDate($row['od_date']); $memberEntity->setMbNameLst($row[„mb_name_last']);
$orderEntity->setOdTotal($row['od_total']); $memberEntity->setMbNameFirst($row[„mb_name_first']);
$orderEntity->setOdName($row['od_name']); $memberEntity->setMbMail($row[„mb_mail']);
$orderEntity->setOdAddress($row['od_address']); }
$orderEntity->setOdTel($row['od_tel']); }
} catch(PDOException $ex) {
} $expMessage = "<p>DB接続に失敗しました。<hr/>";
catch(PDOException $ex) { print($expMessage);
$expMessage = "<p>DB接続に失敗しました。 }
<hr/>"; return $memberEntity;
print($expMessage); }
} }
return $orderEntity; ?>
}
}
?>
- 92. Viewは…
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CakePHP Sample01</title>
</head>
<body>
<header>
<h1>CakePHP Sample01</h1>
</header>
<section>
<table border="1">
<tr>
<th>注文コード</th>
<td><?php print($data['Order']['od_code'])?></td>
</tr>
<tr>
<th>注文日時</th>
<td><?php print(strftime('%Y/%m/%d %H:%M:%S',strtotime($data['Order']['od_date'])))?></td>
</tr>
<tr>
<th>注文合計金額</th>
<td><?php print(number_format($data['Order']['od_total']))?>円</td>
</tr>
<tr>
<th>注文者氏名</th>
<td><?php print($data['Order']['od_name'])?></td>
</tr>
<tr>
<th>注文者住所</th>
<td><?php print($data['Order']['od_address'])?></td>
</tr>
<tr>
<th>注文者電話番号</th>
<td><?php print($data['Order']['od_tel'])?></td>
</tr>
</table>
</section>
</body>
</html>
- 103. 通常のControllerは…
例えば、こんなアプリと
して
showList.php showOneLine.php
表示画面 処理 表示画面 処理 表示画面
http://…/wow/hoge/showList.php
http://…/wow/hoge/ showOneLine.php
- 104. CakePHPのControllerは…
表示画面 処理 表示画面 処理 表示画面
<?php
class HogeController extends AppController {
public $name = 'Hoge';
function showList() {
…
}
function showOneLine() {
…
}
}
?>
http://…/wow/hoge/showList
http://…/wow/hoge/ showOneLine
- 109. Viewにデータを送る方法
Controllerの各メソッド内で、
$this->set(“変数名”, 値)
View側では普通に変数として使用する
<?php
class HogeController extends AppController {
function showList() {
…
<td><?php print($list)?></td>
$this->set(„list', $listData);
}
}
?>
- 114. SELECT系基本2
第2引数$paramsはオプ
ション設定の連想配列(省 $params = array(
'conditions' => array('Model.field' => $thisValue),
略可)。主なものは以下の 'recursive' => 1,
通り。 'fields' =>
array('Model.field1', 'DISTINCT Model.field2'),
conditions: 条件。WHERE 'order' =>
句に該当 array('Model.created', 'Model.field3 DESC'),
'group' => array('Model.field'),
fields: 取得するフィールド 'limit' => 15,
'page' => 3,
order: 取得順。ORDER BY 'offset' => 4,
に該当。 'callbacks' => true
)
group: グループ化。
GROUP BYに該当。
- 115. findの結果
Modelの取得結果は連想配列 Array
(
に格納されている。 [0] => Array
(
[Member] => Array
(
[id] => 1
[mb_name_last] => 安室
[mb_name_first] => 令
[mb_mail] => rey@amuro.com
$memberList = $this->Member->find('all'); )
)
[1] => Array
(
[Member] => Array
(
[id] => 2
[mb_name_last] => 神湯
[mb_name_first] => 美談
[mb_mail] => kamille@bidan.com
)
)
)
- 118. $newMember = array(
"mb_name_first"=>"枢木",
"mb_name_last"=>"朱雀",
"mb_mail"=>"suzaku@kururugi.net" INSERT
);
$this->Member->save($newMember);
$oldMember = array(
"id"=>4,
"mb_mail"=>"suzaki@kururugi.com" UPDATE
);
$this->Member->save($oldMember);
その他、詳細は本家サイトのマニュアルを参照。
http://book.cakephp.org/2.0/en/models/saving-your-data.html
- 119. DELETE
削除(DELETE)は
delete($id, $cascade)
第1引数$idは主キー値。
$this->Member->delete(4);
第2引数$cascadeは省略可。
関連テーブルのレコードも削除するかどうかをtrueかfalseで指
定。
条件指定の削除は
deleteAll($conditions, $cascade, $callbacks)
第1引数$conditionsに条件を表す連想配列を指定。
第2引数第3引数は省略可。
$this->Member->deleteAll(array("mb_mail"=>"suzaki@kururugi.com"));
その他、詳細は本家サイトのマニュアルを参照。
http://book.cakephp.org/2.0/en/models/deleting-data.html
- 121. Relation
RDBのRはリレーション。
Modelでリレーションを設定 public $hasMany = array(
„Membergroup' => array(
するには、以下のフィール „className' => „Membergroup',
ドを設定する。 „foreignKey' => „member_id„
)
$hasOne );
$hasMany
belongsTo
hasAndBelongsToMany
詳細は本家サイトのマニュアルを参照。
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
- 122. Validation
必須チェックや数値 public $validate = array(
„mb_name_last' => array(
チェックなど、Model側 „notempty' => array(
で各カラムのValidationが „rule' => array(„notempty„),
„message‟ => „名前(姓)は必須です。'
できる。 )
)
$validateフィールドに );
ルールを記述。
詳細は本家サイトのマニュアルを参照。
http://book.cakephp.org/2.0/en/models/data-validation.html
- 124. Transactions
トランザクション $dataSource = $this->Member->getDataSource();
$dataSource->begin();
制御も可能。 $memberResult = $this->Member->save($newMember);
$orderResult = $this->Order->save($newOrder);
オススメは if(…) {
Controllerで制御。 $dataSource->commit();
}
else(…) {
$dataSource->rallback();
}
詳細は本家サイトのマニュアルを参照。
http://book.cakephp.org/2.0/en/models/transactions.html
- 133. ところで、
CakePHPの
Viewに注目してみる
- 135. ソースコードは…
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CakePHP Sample02</title>
</head>
<body>
<header>
<h1>CakePHP Sample02</h1>
</header>
<section>
<?php if(empty($memberList)) { ?>
<p>表示すべき情報はありません。</p>
<?php }
else { ?>
<?php print(count($memberList)) ?>件ありました。
<table border="1">
<thead>
<tr>
<th>会員コード</th>
<th>会員名</th>
<th>メールアドレス</th>
</tr>
</thead>
<tbody>
<?php foreach($memberList as $key=>$member) { ?>
<tr>
<td><?php print($member['Member']['id']) ?></td>
<td><?php print($member['Member']['mb_name_last']." ".$member['Member']['mb_name_first']) ?></td>
<td><?php print($member['Member']['mb_mail']) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</section>
</body>
</html>
- 151. ちなみに…
Smarty連携の項目自体
がなくなっていた…
- 157. ということで、
不肖新三
このソースを改造して
とりあえず
動くようにしました!
- 162. CakePHP+Smarty準備手順3
Smarty View Classのインストール
SmartyView.phpファイルを入手し、
cakephpの
app/View
直下に配置する。
入手は、この勉強会のサンプル自体を
github
https://github.com/architshin/histudy7
に置いてあるので、このリポジトリの
histudy7/cakesmarty/app/View/SmartyView.php
を参照。
- 165. Controller
<?php
class MemberController extends AppController {
public $name = 'Member';
public $uses = array('Member');
public $viewClass = 'Smarty';
function showList() {
$memberList = $this->Member->find('all');
$this->set('memberList', $memberList);
$this->set('memberListCount', count($memberList));
}
}
?>
- 166. View: show_list.tpl(一部)
<section>
{if empty($memberList) }
<p>表示すべき情報はありません。</p>
{else}
{$memberListCount}件ありました。
<table border="1">
<thead>
<tr>
<th>会員コード</th>
<th>会員名</th>
<th>メールアドレス</th> Smartyでは配列のアクセスは
</tr> $member[‘Member’][‘id’]
</thead>
<tbody>
ではなく、
{foreach from=$memberList item="member"} 「.」でつなぐ
<tr>
<td>{$member.Member.id}</td>
<td>{$member.Member.mb_name_last} {$member.Member.mb_name_first}</td>
<td>{$member.Member.mb_mail}</td>
</tr>
{/foreach}
</tbody>
</table>
{/if}
</section>