2009-02-15
Ajax を使ってチャットする
================================================================================
■chat.html
---
XMLHttpRequest
---
■chat1.php
---
contents = array();
foreach (ChatDao::getChatList($connection, 20) as $e) {
$res->contents[] = $e->__toString();
}
// データベースを切断する。
$connection->disconnect();
} catch (Exception $e) {
// 例外が起きた場合、メッセージを組み立てる。
$res->message->level = 1;
$res->message->content = $e->getMessage();
}
// レスポンスをエンコードする。
echo json_encode($res);
?>
---
■Chat.class.php
---
setId($id);
$this->setName($name);
$this->setContent($content);
$this->setCreatedAt($createdAt);
}
/**
* IDを取得する。
* @return ID
*/
public function getId() {
return $this->id;
}
/**
* IDを設定する。
* @param $id ID
*/
public function setId($id) {
$this->id = $id;
}
/**
* 名前を取得する。
* @return 名前
*/
public function getName() {
return $this->name;
}
/**
* 名前を設定する。
* @param $name 名前
*/
public function setName($name) {
$this->name = $name;
}
/**
* 内容を取得する。
* @return 内容
*/
public function getContent() {
return $this->content;
}
/**
* 内容を設定する。
* @param $content 内容
*/
public function setContent($content) {
$this->content = $content;
}
/**
* 作成日時を取得する。
* @return 作成日時
*/
public function getCreatedAt() {
return $this->createdAt;
}
/**
* 作成日時を設定する。
* @param $createdAt 作成日時
*/
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
}
/**
* このインスタンスの文字列表現
* @return このインスタンスの文字列表現
*/
public function __toString() {
return "[{$this->id}, {$this->name}, {$this->content}, {$this->createdAt}]";
}
}
?>
---
■ChatDao.class.php
---
getMessage());
}
return $connection;
}
/**
* チャットのデータを20件分取得する。
* @param $connection
* @param $limit 取得する行数
* @return 勝敗数
*/
public static function getChatList($connection, $limit = 20) {
$sql = "SELECT id, name, content, created_at FROM ajax_chat ORDER BY id DESC LIMIT {$limit} ";
$res = $connection->query($sql);
if (PEAR::isError($res)) {
throw new Exception($res->getMessage());
}
while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
$chatList[] = new Chat($row['name'], $row['content'], $row['id'], $row['created_at']);
}
return $chatList;
}
/**
* チャットを記録する。
* @param $name
* @param $content
* @param $connection
*/
public static function record($chat, $connection) {
$sql = "INSERT INTO ajax_chat VALUES(DEFAULT, '{$chat->getName()}', '{$chat->getContent()}', CURRENT_TIMESTAMP)";
$res = $connection->query($sql);
if (PEAR::isError($res)) {
throw new Exception($res->getMessage());
}
}
/**
* 名前で指定された結果表のデータをクリアする。
* @param $name
* @param $connection
*/
public static function clearBy($name, $connection) {
$sql = "DELETE FROM ajax_chat WHERE name = '{$name}'";
$res = $connection->query($sql);
if (PEAR::isError($res)) {
throw new Exception($res->getMessage());
}
}
/**
* データをクリアする。
* @param $connection
*/
public static function clear($connection) {
$sql = "TRUNCATE ajax_chat ";
$res = $connection->query($sql);
if (PEAR::isError($res)) {
throw new Exception($res->getMessage());
}
}
}
?>
---
■Message.class.php
---
---
以上