■ここでときたいこと
mysqlからデータを取得して、ページを表示する方法。


■テーブルの生成
※通常ですと、zf create db-table User
としたいところですが、ここでは、テーブルの作成から入っています。

※Mysql Query Browserを利用してつくります。が、別に何でもいいです。

DROP TABLE IF EXISTS `zf_001`.`t_user`;
CREATE TABLE `zf_001`.`t_user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_uid` text NOT NULL,
`user_utn` text NOT NULL,
`user_guid` text NOT NULL,
`user_name` text NOT NULL,
`user_pass` text NOT NULL,
`user_created_dt` datetime NOT NULL,
`user_enabled` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

※CHARSET=utf8にしています。


適当にデータを入れます。
-------------------------
user_id : 1
user_uid : NULLGWDOCOMO
user_utn : UTN
user_guid : GUID
user_name : ビー玉のお京
user_pass : qwerty
user_created_ts : 2010-05-17 00:00:00
user_enabled : 1
-------------------------


■/application/config/application.configの設定
DB接続するための設定をコンフィグファイルに書き込みます。
---------------------------------------------------------------
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.dbname = "zf_001"
resources.db.params.username = "root"
resources.db.params.password = "自分でつけたパスワード"
resources.db.params.charset = "utf8"
---------------------------------------------------------------

ここでもutf8に設定しています。


■/application/models/User.php
モデルクラスUserをつくります。
t_userのフィールドと、get/setを作っています。
---------------------------------------------------------------

<?php

// application/models/User.php
class Application_Model_User
{
protected $_user_id;
protected $_user_uid;
protected $_user_utn;
protected $_user_guid;
protected $_user_name;
protected $_user_pass;
protected $_user_created_dt;
protected $_user_enabled;

public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}

public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid guestbook property');
}
$this->$method($value);
}

public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid guestbook property');
}
return $this->$method();
}

public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setUserId($text){
$this->_user_id = (string) $text;
return $this;
}
public function getUserId(){
return $this->_user_id;
}
public function setUserUid($text){
$this->_user_uid = (string) $text;
return $this;
}
public function getUserUid(){
return $this->_user_uid;
}
public function setUserGuid($text){
$this->_user_guid = (string) $text;
return $this;
}
public function getUserUtn(){
return $this->_user_utn;
}
public function setUserUtn($text){
$this->_user_utn = (string) $text;
return $this;
}
public function getUserGuid(){
return $this->_user_guid;
}
public function setUserName($text){
$this->_user_name = (string) $text;
return $this;
}
public function getUserName(){
return $this->_user_name;
}
public function setUserPass($text){
$this->_user_pass = (string) $text;
return $this;
}
public function getUserPass(){
return $this->_user_pass;
}
public function setUserCreatedDt($text){
$this->_user_created_dt = (string) $text;
return $this;
}
public function getUserCreatedDt(){
return $this->_user_created_dt;
}
public function setUserEnabled($text){
$this->_user_enabled = (string) $text;
return $this;
}
public function getUserEnabled(){
return $this->_user_enabled;
}
}

?>
---------------------------------------------------------------



■/application/models/UserMapper.php
User.phpとDBのt_userとのマッピングを行うクラスです。

---------------------------------------------------------------
<?php
// application/models/UserMapper.php

class Application_Model_UserMapper
{
protected $_dbTable;

/**
* これはデフォルト。たぶんスーパークラスで持たせるほうがよい。
*/
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}

/**
* これはデフォルト
*/
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_User');
}
return $this->_dbTable;
}

public function save(Application_Model_User $user)
{
$data = array(
'user_id' => 'default',
'user_uid' => $user->getUid(),
'user_guid' => $user->getGuid(),
'user_utn' => $user->getUtn(),
'user_name' => $user->getName(),
'user_pass' => $user->getPass(),
'user_created_dt' => 'default',
'user_enabled' => 'default',
);

if (null === ($id = $user->getUserId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('user_id = ?' => $user_id));
}
}

public function find($user_id, Application_Model_User $user)
{
$result = $this->getDbTable()->find($user_id);
if (0 == count($result)) {
return;
}
$row = $result->current();
$user->setUserId($row->user_id)
->setUserUid($row->user_uid)
->setUserUtn($row->user_utn)
->setUserGuid($row->user_guid)
->setUserName($row->user_name)
->setUserPass($row->user_pass)
->setUserCreatedDt($row->user_created_dt)
->setUserEnabled($row->user_enabled);
}

public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_User();
$entry->setUserId($row->user_id)
->setUserUid($row->user_uid)
->setUserUtn($row->user_utn)
->setUserGuid($row->user_guid)
->setUserName($row->user_name)
->setUserPass($row->user_pass)
->setUserCreatedDt($row->user_created_dt)
->setUserEnabled($row->user_enabled);
$entries[] = $entry;
}
return $entries;
}
}

?>
---------------------------------------------------------------


■/application/controller/User.php
コントローラクラスです。これは、
controllerは、コマンドから生成しています。
アプリケーションのホームディレクトリにて実行します。
---------------------------------------------------------------
C:\svn\www\zf_001>zf create controller User
Creating a controller at C:\svn\www\zf_001/application/controllers/UserControlle
r.php
Creating an index action method in controller User
Creating a view script for the index action method at C:\svn\www\zf_001/applicat
ion/views/scripts/user/index.phtml
Creating a controller test file at C:\svn\www\zf_001/tests/application/controlle
rs/UserControllerTest.php
Updating project profile 'C:\svn\www\zf_001/.zfproject.xml'

C:\svn\www\zf_001>
---------------------------------------------------------------

■/application/views/user/index.phtmlの編集
つづいてviewの編集です。
通常
$user->getUserId()

viewないでは、
$entry->userid
getがとれて、大文字小文字もなくなっていることに注意です。

---------------------------------------------------------------
<!-- application/views/scripts/user/index.phtml -->

User Entries:

<dl>
<?php foreach ($this->entries as $entry): ?>
<dt><?php echo $this->escape($entry->userid) ?></dt>
<dd><?php echo $this->escape($entry->useruid) ?></dd>
<dd><?php echo $this->escape($entry->userutn) ?></dd>
<dd><?php echo $this->escape($entry->userguid) ?></dd>
<dd><?php echo $this->escape($entry->username) ?></dd>
<dd><?php echo $this->escape($entry->userpass) ?></dd>
<dd><?php echo $this->escape($entry->usercreateddt) ?></dd>
<dd><?php echo $this->escape($entry->userenabled) ?></dd>
<?php endforeach ?>
</dl>
---------------------------------------------------------------

■一度apacheを再起動して確認。
http://dev.zf_001/user/
にアクセスをして確認。
---------------------------------------------------------------
User Entries:
user_id : 1
user_uid : NULLGWDOCOMO
user_utn : UTN
user_guid : GUID
user_name : ビー玉のお京
user_pass : qwerty
user_created_dt : 2010-05-17 00:00:00
user_enabled : 1
---------------------------------------------------------------
と表示されます。

※User/UserMapperの修正には気をつけましょう。
結構間違える。
エラー画面が出てくると思うので、都度確認しましょう。


■これまでに解決したこと
[OK]windows+mysql+apache+php+zendframeworkでページを表示する方法。
[OK]mysqlからデータを取得して、ページを表示する方法。
[OK]DBの文字コードの設定方法。

■疑問点
[NG]複数DBへの接続の設定方法。
[NG].zfproject.xmlって何の役割をするの?



■何をするの?
ZendFrameworkをうごかす。
windows上で動かす。
apacheを使って動かす。


■ダウンロード
・mysql
・apache
・php
・ZendFramework


■mysqlのインストール
このあたりはスルーで。
※詳細必要な人は、コメントに記入してください。


■mysql administratorのインストール
mysqlのguiツールのダウンロード。ここから落とす。
http://dev.mysql.com/downloads/administrator/
インストールすると、
QueryBrowserがインストールされるので、それを使って、mysqlの管理をします。


■apacheのインストール
www.apache.org
から落としてくる。

細かいところは割愛。※詳細必要な人は、コメントに記入してください。


※mod_rewrite利用できる状態になっているかどうか確認してください。
ZendFrameworkで利用します。


■phpのインストール
インストールの際
extの設定を
mbstring
pdo
pdo_mysql
などにチェックをつける。

※拡張モジュールに全部チェックつけたりすると、エラーだらけになってえらいことになります。
必要なものだけチェックしてください。


■ZendFrameworkのダウンロード
ダウンロードして回答。
おいらは、下記のフォルダーにコピー。
C:\svn\ZendFramework-1.10.4
とかにする。


■ZendFrameworkのパスの設定
環境変数PATHに下記を追加する。
C:\svn\ZendFramework-1.10.4\bin


■php.iniの確認
・include_pathの設定
Zendのライブラリのパスをinclude_pathに追加する。
C:\svn\ZendFramework-1.10.4\library

----------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
include_path = ".;c:\php\includes;C:\svn\ZendFramework-1.10.4\library"
----------------------------------------------------------------


・mbstring / pdoの設定
大体こんな感じ。

----------------------------------------------------------------
[PHP_MBSTRING]
extension=php_mbstring.dll
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_PDO]
extension=php_pdo.dll
[PHP_PDO_MYSQL]
extension=php_pdo_mysql.dll
----------------------------------------------------------------

※C:\Program Files\PHP
本来であれば、
C:\Program Files\PHP
のdllにパスを通さないといけないのですが、時間がなかったので
libmysql.dllとかを
C:\WINDOWS\system32
コピーしています。これをしないとアパッチが起動しない場合があります。


■httpd.confの設定

・phpモジュールの設定
apacheをインストールした後に、phpをインストールすると
apacheのconfフォルダーを聞かれるので、そのとおりに設定すると
下記のようにhttpd.confに書き加えてくれます。

----------------------------------------------------------------
#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "C:/Program Files/PHP/"
LoadModule php5_module "C:/Program Files/PHP/php5apache2_2.dll"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
----------------------------------------------------------------

・VirtuahHostの設定

----------------------------------------------------------------
NameVirtualHost *:80
Include conf/extra/httpd-vhosts-localhost.conf
#Include conf/extra/httpd-vhosts-zf_001.conf
----------------------------------------------------------------

※#Include conf/extra/httpd-vhosts-zf_001.conf
はあとでつかいます。


■conf/extra/httpd-vhosts-localhost.conf
単にデフォルトの設定を行っているだけです。

----------------------------------------------------------------
<VirtualHost *:80>
ServerName localhost
DocumentRoot C:\svn\www

<Directory C:\svn\www>
DirectoryIndex index.php index.html
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
----------------------------------------------------------------


■C:\svn\www\info.phpの作成
ZendFrameworkを試す前に、ここまでの設定がうまくいっているかどうか確認するためのphpスクリプトを作成します。
内容は下記のとおりです。

----------------------------------------------------------------
<?php
phpinfo();
?>
----------------------------------------------------------------


■アパッチの起動
アパッチを起動して、
http://localhst/info.php
にアクセスします。
このときそのページをpdoで検索をかけて下記のようなものがあれば、pdoが利用できる状態にあります。
mysqlとpgsqlが利用できる状態です。

+---------------------------+
| PDO |
+-------------+-------------+
|PDO support | enabled |
|PDO drivers | mysql, pgsql|
+-------------+-------------+


■ZendFramework のプロジェクト作成
ここでは、
C:\svn\www\

zf_001
というプロジェクトを作ります。
コマンドプロンプトで
cd C:\svn\www\
に移動した後、

----------------------------------------------------------------
C:\svn\www>zf create project zf_001
----------------------------------------------------------------

を実行すると、ruby on rails のように、だだーとフォルダができて、アプリケーションが配備されます。フォルダーの構成については、ここでは割愛します。
が、
zf_001\public
というフォルダーがドキュメントルートになります。
なので次のVirtualHostの設定の際には、
C:\svn\www\zf_001\public
で設定します。


■Apache : conf/extra/httpd-vhosts-zf_001.confの作成
下記のとおり、設定を行います。
SetEnv APPLICATION_ENV "development"
は環境変数を設定するものです。
ここでは、

http://dev.zf_001/
にアクセスしたら、ZendFrameworkのページが見られるようにします。


<VirtualHost *:80>
ServerName dev.zf_001
DocumentRoot C:\svn\www\zf_001\public

SetEnv APPLICATION_ENV "development"

<Directory C:\svn\www\zf_001\public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>


■Apache : conf/httpd.confの修正
・VirtualHostの設定
さっきのコメントをはずます。
最終的には下記のとおりになります。

httpd.conf 一番下

----------------------------------------------------------------
NameVirtualHost *:80
Include conf/extra/httpd-vhosts-localhost.conf
Include conf/extra/httpd-vhosts-zf_001.conf
----------------------------------------------------------------

・アクセス制限の確認
大本のディレクトリのアクセス制限について確認します。
インストール直後は下記のようになっています。

httpd.conf 188行目ぐらい

----------------------------------------------------------------
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
----------------------------------------------------------------

最終的に下記のように設定してください。

----------------------------------------------------------------
<Directory />
Options All
AllowOverride All
#Order deny,allow
#Deny from all
</Directory>
----------------------------------------------------------------

※mod_rewriteについて
mod_rewrite利用できる状態になっているかどうか確認してください。
ZendFramework 1.10.4では、
public\.htaccessに

----------------------------------------------------------------
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
----------------------------------------------------------------

のような記述があります。


■hostsの設定
C:\WINDOWS\system32\drivers\etc\hosts
を編集します。
127.0.0.1 dev.zf_001
を追記してください。

----------------------------------------------------------------
127.0.0.1 localhost
127.0.0.1 dev.zf_001
----------------------------------------------------------------


■アパッチ再起動
再起動して

http://localhost/info.php
http://dev.zf_001/
にそれぞれアクセスして、違うページが表示されることを確認します。


うまく表示されればOKです。


■アパッチがうまく起動せず、エラー画面が表示される場合
phpの拡張モジュールがうまく設定されていない場合があります。

私が経験したのは、
dllファイルのパスの設定が適切にされていないようで、その場合は先述したとおり
C:\Program Files\PHP
にある
dllファイルを
C:\WINDOWS\system32
に持っていけば起動します。

環境変数のPathに
C:\Program Files\PHP
を追記すればいいと他のサイトに書いてあったりするのですが、なぜかうまくいきませんでした。


■疑問点
・mysqlからデータを取得して、ページを表示する方法。
・複数DBへの接続の設定方法。
・DBの文字コードの設定方法。