(1)
(0)
(0)
(0)
Total: 1 DAY2: データモデルの作成
昨日はsymfonyのセットアップと画面をブラウザで表示させるところまでいきました。
今日はアプリケーションで使用するデータモデルを作成していきます。
ところでaskeetって何?
askeetとはQ&Aサイトです。質問を投稿し、それに答えて、"イイネ"をつけるようなアプリケーションです。
データモデルの設計
以下の図のようなテーブル設計になっています。
question: 質問内容 answer: 回答内容 user: ユーザー interest: userテーブルとquestionテーブルとの多対多のリレーションテーブル relevancy: userテーブルとanswerテーブルとの多対多のリレーションテーブル
symfonyでテーブルを設計する場合はレコードの作成日、更新日はcreated_at, updated_atにするルールがあります。
必須ではないのですが、このルールに従っておけばORマッパーが自動的に判断してくれるのです。
schema.xml
本家ではschema.xmlを利用してテーブル定義を書き、そのスキーマファイルから物理的なテーブルを作成しています。
ref: http://www.symfony-project.org/askeet/1_0/en/2#%3Ccode%3Eschema.xml%3C/code%3E
しかし、ここではこの方法を用いずに、物理的なテーブルを最初に作成する方法を紹介します。
本家のようにスキーマファイルを最初から書かないメリットは何でしょうか?
それは、既に身に付けているSQLの知識さえあれば良く、スキーマの構文を覚える必要がないということです。
もちろんスキーマファイルはSQLよりも短く書く事ができます。しかし、phpMyAdminなどを利用すれば単純なミスから解放されるでしょう。
というわけで、スキーマファイルを意識せずにデータモデルを作成したいと思います。
phpMyAdminでテーブル設計
まず今回のデータベースの接続情報は以下のようになっています。
DB: MySQL
Database: askeet
User: yourname
Password: yourpasswod
ユーザーとデータベースを作成しておきます。
mysql> grant all privileges on askeet.* to yourname@"%" identified by 'yourpassword';
Query OK, 0 rows affected (0.00 sec)mysq> create database askeet;
Query OK, 1 row affected (0.00 sec)
次にテーブルのcreate文をphpMyAdminで作成しておきます。
今回は実際に作成したテーブルのcreate文をエクスポートしたものが下記になります。
これを利用する場合はSQLをdata/sql/create.sqlとして保存しておきます。
$ mkdir -p /home/sfprojects/askeet/data/sql/
$ vim /home/sfprojects/askeet/data/sql/create.sql
-
-- phpMyAdmin SQL Dump
-
-- version 2.11.5.1
-
-- http://www.phpmyadmin.net
-
--
-
-- ホスト: localhost
-
-- 生成時間: 2008 年 10 月 21 日 03:54
-
-- サーバのバージョン: 5.0.67
-
-- PHP のバージョン: 5.2.6
-
-
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
-
-
--
-
-- データベース: `askeet`
-
--
-
-
-- --------------------------------------------------------
-
-
--
-
-- テーブルの構造 `ask_answer`
-
--
-
-
CREATE TABLE IF NOT EXISTS `ask_answer` (
-
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
-
`question_id` int(10) UNSIGNED NOT NULL,
-
`user_id` int(10) UNSIGNED NOT NULL,
-
`body` text NOT NULL,
-
`created_at` datetime NOT NULL,
-
PRIMARY KEY (`id`),
-
KEY `question_id` (`question_id`,`user_id`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-
-
--
-
-- テーブルのデータをダンプしています `ask_answer`
-
--
-
-
-- --------------------------------------------------------
-
-
--
-
-- テーブルの構造 `ask_interest`
-
--
-
-
CREATE TABLE IF NOT EXISTS `ask_interest` (
-
`question_id` int(10) UNSIGNED NOT NULL,
-
`user_id` int(10) UNSIGNED NOT NULL,
-
`created_at` datetime NOT NULL,
-
PRIMARY KEY (`question_id`,`user_id`),
-
KEY `user_id` (`user_id`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
-
--
-
-- テーブルのデータをダンプしています `ask_interest`
-
--
-
-
-- --------------------------------------------------------
-
-
--
-
-- テーブルの構造 `ask_question`
-
--
-
-
CREATE TABLE IF NOT EXISTS `ask_question` (
-
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
-
`user_id` int(10) UNSIGNED NOT NULL,
-
`title` text NOT NULL,
-
`body` text NOT NULL,
-
`created_at` datetime NOT NULL,
-
`updated_at` datetime NOT NULL,
-
PRIMARY KEY (`id`),
-
KEY `user_id` (`user_id`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-
-
--
-
-- テーブルのデータをダンプしています `ask_question`
-
--
-
-
-- --------------------------------------------------------
-
-
--
-
-- テーブルの構造 `ask_relevancy`
-
--
-
-
CREATE TABLE IF NOT EXISTS `ask_relevancy` (
-
`answer_id` int(10) UNSIGNED NOT NULL,
-
`user_id` int(10) UNSIGNED NOT NULL,
-
`score` int(11) NOT NULL,
-
`created_at` datetime NOT NULL,
-
PRIMARY KEY (`answer_id`,`user_id`),
-
KEY `user_id` (`user_id`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
-
--
-
-- テーブルのデータをダンプしています `ask_relevancy`
-
--
-
-
-- --------------------------------------------------------
-
-
--
-
-- テーブルの構造 `ask_user`
-
--
-
-
CREATE TABLE IF NOT EXISTS `ask_user` (
-
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
-
`nickname` varchar(50) NOT NULL,
-
`first_name` varchar(100) DEFAULT NULL,
-
`last_name` varchar(100) DEFAULT NULL,
-
`created_at` datetime NOT NULL,
-
PRIMARY KEY (`id`),
-
KEY `nickname` (`nickname`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-
-
--
-
-- テーブルのデータをダンプしています `ask_user`
-
--
-
-
--
-
-- ダンプしたテーブルの制約
-
--
-
-
--
-
-- テーブルの制約 `ask_answer`
-
--
-
ALTER TABLE `ask_answer`
-
ADD CONSTRAINT `ask_answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `ask_question` (`id`);
-
-
--
-
-- テーブルの制約 `ask_interest`
-
--
-
ALTER TABLE `ask_interest`
-
ADD CONSTRAINT `ask_interest_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `ask_user` (`id`),
-
ADD CONSTRAINT `ask_interest_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `ask_question` (`id`);
-
-
--
-
-- テーブルの制約 `ask_question`
-
--
-
ALTER TABLE `ask_question`
-
ADD CONSTRAINT `ask_question_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `ask_user` (`id`);
-
-
--
-
-- テーブルの制約 `ask_relevancy`
-
--
-
ALTER TABLE `ask_relevancy`
-
ADD CONSTRAINT `ask_relevancy_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `ask_user` (`id`),
-
ADD CONSTRAINT `ask_relevancy_ibfk_1` FOREIGN KEY (`answer_id`) REFERENCES `ask_answer` (`id`);
このcreate.sqlでテーブルを作成する場合は以下のようにすればできるのは周知の内容です。
$ mysql -uyourname -p askeet < /home/sfprojects/askeet/data/sql/create.sql
さぁ、実際のテーブルからデータモデルのコードを自動生成させましょう。
ここで大きな2つの選択肢があります。
それはORマッパーとしてPropelかDoctrineのどちらかを使う事ができるからです。
symfony1.1まではPropelが標準でしたがDoctrineが直感的に書ける点で人気があります。
本家ではPropelを使っているのでここではDoctrineを使う事にしましょう。
これらのORマッパーはプラグインとして提供されています。
そのため、プラグインの有効無効を設定する必要があります。
プラグインの設定は ./config/ProjectConfiguration.class.php で行います。
$ vim ./config/ProjectConfiguration.class.php
-
public function setup()
-
{
-
$this->enablePlugins('sfDoctrinePlugin');
-
$this->disablePlugins('sfPropelPlugin');
-
}
次にsymfonyに接続情報を記述しなくてはいけません。
接続情報は./config/database.ymlに記述します。
ここでyml(ヤムル)ファイルという種類のファイルがあることがわかります。
これはXMLよりも可読性の高い構造を表すことができるファイルです。
詳しくは下記サイトを見ると数十分で理解できるでしょう。
ref: http://jp.rubyist.net/magazine/?0009-YAML
では、設定をかきましょう。
$ vim ./config/database.yml
-
all:
-
main:
-
class: sfDoctrineDatabase
-
param:
-
dsn: 'mysql:host=localhost;dbname=askeet'
-
username: yourname
-
password: yourpassword
さぁ、これで準備ができました。
さっそくデータベースからスキーマファイルを自動生成させてみましょう。
どのコマンドを叩くのか解らない場合はlistコマンドで確認できます。
doctrineで用意されているタスクをlist doctrineコマンドで確認してみます。
$ ./symfony list doctrine
:build-all Generates Doctrine model, SQL and initializes the database (doctrine-build-all)
:build-all-load Generates Doctrine model, SQL, initializes database, and load data (doctrine-build-all-load)
:build-all-reload Generates Doctrine model, SQL, initializes database, and load data (doctrine-build-all-reload)
:build-all-reload-test-all Generates Doctrine model, SQL, initializes database, load data and run all test suites (doctrine-build-all-reload-test-all)
:build-db Creates database for current model (doctrine-build-db)
:build-filters Creates filter form classes for the current model
:build-forms Creates form classes for the current model (doctrine-build-forms)
:build-model Creates classes for the current model (doctrine-build-model)
:build-schema Creates a schema from an existing database (doctrine-build-schema)
:build-sql Creates SQL for the current model (doctrine-build-sql)
:data-dump Dumps data to the fixtures directory (doctrine-dump-data)
:data-load Loads data from fixtures directory (doctrine-load-data)
:dql Execute a DQL query and view the results (doctrine-dql)
:drop-db Drops database for current model (doctrine-drop-db)
:generate-migration Generate migration class (doctrine-generate-migration)
:generate-migrations-db Generate migration classes from existing database connections (doctrine-generate-migrations-db, doctrine-gen-migrations-from-db)
:generate-migrations-models Generate migration classes from an existing set of models (doctrine-generate-migrations-models, doctrine-gen-migrations-from-models)
:generate-module Generates a Doctrine module (doctrine-generate-crud, doctrine:generate-crud)
:generate-module-for-route Generates a Doctrine module for a route definition
:init-admin Initializes a Doctrine admin module (doctrine-init-admin)
:insert-sql Inserts SQL for current model (doctrine-insert-sql)
:migrate Migrates database to current/specified version (doctrine-migrate)
:rebuild-db Creates database for current model (doctrine-rebuild-db)
今回利用するのはbuild-schema, build-modelです。
$ ./symfony doctrine:build-schema
>> doctrine generating yaml schema from database
これで./config/doctrine/schema.ymlが作成されました。
askeetのチュートリアルでは実際のテーブル名とモデル名が異なります。
テーブル名にはask_という接頭辞がついています。
そこで、./config/doctrine/schema.ymlで各テーブルのモデル名を変更しておきます。
$ vim ./config/doctrine/schema.yml
ここで先頭のモデル名を
-
AskInterest:
-
tableName: ask_interest
-
columns:
から
-
Interest:
-
tableName: ask_interest
-
columns:
とAsk部分を取り除いておきます。
また、MySQLのTEXTタイプがstring(2146483647)に解釈されています。
このままですとフォームを自動生成させたときにtextareaとして認識されませんので
clobに変更しておきます。
以下のようなschema.ymlが完成形です。
-
Interest:
-
tableName: ask_interest
-
columns:
-
question_id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
user_id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
created_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
relations:
-
User:
-
local: user_id
-
foreign: id
-
type: one
-
Question:
-
local: question_id
-
foreign: id
-
type: one
-
Question:
-
tableName: ask_question
-
columns:
-
id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
autoincrement: true
-
user_id:
-
type: integer(4)
-
unsigned: 1
-
default: ''
-
notnull: true
-
title:
-
type: clob
-
default: ''
-
notnull: true
-
body:
-
type: clob
-
default: ''
-
notnull: true
-
created_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
updated_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
relations:
-
User:
-
local: user_id
-
foreign: id
-
type: one
-
User:
-
tableName: ask_user
-
columns:
-
id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
autoincrement: true
-
nickname:
-
type: string(50)
-
default: ''
-
notnull: true
-
created_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
first_name: string(100)
-
last_name: string(100)
-
Relevancy:
-
tableName: ask_relevancy
-
columns:
-
answer_id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
user_id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
score:
-
type: integer(4)
-
default: ''
-
notnull: true
-
created_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
relations:
-
User:
-
local: user_id
-
foreign: id
-
type: one
-
Answer:
-
local: answer_id
-
foreign: id
-
type: one
-
Answer:
-
tableName: ask_answer
-
columns:
-
id:
-
type: integer(4)
-
unsigned: 1
-
primary: true
-
autoincrement: true
-
question_id:
-
type: integer(4)
-
unsigned: 1
-
default: ''
-
notnull: true
-
user_id:
-
type: integer(4)
-
unsigned: 1
-
default: ''
-
notnull: true
-
body:
-
type: clob
-
default: ''
-
notnull: true
-
created_at:
-
type: timestamp(25)
-
default: ''
-
notnull: true
-
relations:
-
Question:
-
local: question_id
-
foreign: id
-
type: one
ではモデルを作成しましょう。
$ ./symfony doctrine:build-model
>> doctrine generating model classes
これで ./lib/model/doctrine以下に今後修正を加えるファイルが作成されました。
また./lib/model/doctrine/generated以下にもファイルが作成されますが、これはコマンドによって上書きされるファイルです。
このファイルには修正を加えてはいけません。忘れないようにしておきましょう。
フォームクラスを生成する
symfony1.1からはフォームフレームワークが新しく導入されました。
これは以前までyamlやアクションで設定していたフォームに関する処理を委託できるフレームワークです。
綺麗にソースがまとまる反面コーディング方法や内容について理解する必要があるため、
最初は大変かもしれません。ここでは深く触れずに動く物を作ってみます。
モデルの生成と同じで、基底クラスはsymfonyのコマンドで生成することができます。
ではさっくりと作ってしまいましょう。
$ ./symfony doctrine:build-form
>> doctrine generating form classes
作成されたファイルは./lib/form/doctrine以下に生成されます。
CRUDでデータアクセスしてみる
CRUDとはWebアプリケーションで一般的な操作である
Create,Read,Update,Deletenの操作を意味します。
これらの操作の画面をデータモデルから作成するのがCRUDの自動作成になります。
以下のコマンドで簡単にできてしまいます。
$ ./symfony doctrine:generate-module frontend quetion Question
これで,ask_questionを操作するlist, edit. show, index, update, deleteアクションが自動生成されました。
なんとも簡単ですね!
では実際に画面を見てみましょう。
URLはアプリケーション名、モジュール名、アクション名(省略時はindex)になります。
http://symfony.centos5.localhost/frontend_dev.php/question
しかし、ローカル環境でうごかしていない場合は以下のようなエラーが画面に表示されてとまってしまいます。
You are not allowed to access this file. Check frontend_dev.php for more information.
これは、_dev.phpファイルは様々なデバッグ情報を表示するために呼び出すコントローラーなので、
誤って本番にリリースしても動作しないようにIPアドレスでの制限がかかっています。
これを解除する場合はコントローラーファイルを編集し、IPアドレスの制限を外すかIPアドレスを追加します。
$ vim ./web/frontend_dev.php
私の環境では 172.16.203.1で開発サーバーにアクセスするのでこのIPアドレスを以下のように追加しました。
では、画面をみてみましょう!
残念なことにnot nullの項目があるため、データを登録することはできません。
ここまでのソースは
http://svn.1ms.jp/public/symfony/askeet12/tags/release_day_2
から取得することができます。
では、また明日。
関連するその他の記事
Comments
Leave a Reply
