![]() |
symfony 1.4データベース連携
symfonyではPostgreSQLとMySQLのデータベースが使用可能である。symfony 1.0ではpropelを使用してデータベースとの接続を行なっていたが、symfony 1.4ではdoctrineとPDOを使用してデータベースにアクセスする。特にPDOを使用するようになり、データベース接続速度はsymfony 1.0の頃より向上している。
データベース接続を行なう場合に編集するファイルは下記の通りである。
config/databases.yml
config/doctrine/schema.yml
上記のそれぞれのファイルはsymfonyプロジェクトディレクトリ配下に置かれる。
databases.ymlはデータベースとの接続情報を記述し、schama.ymlにはデータベースのテーブル構成を記述する。
databases.ymlの記述例(MySQLを使用する場合)は下記の通り。
# You can find more information about this file on the symfony website:
# http://www.symfony-project.org/reference/1_4/en/07-Databases
all:
doctrine:
class: sfDoctrineDatabase
param:
dsn: mysql:host=localhost;dbname=DBNAME
username: DBUSERNAME
password: DBPASSWORD
encoding: utf8
persistent: true
pooling: true
DBNAMEにはデータベース名を、DBUSERNAMEにはデータベースにアクセス出来るユーザ名を、そしてDBPASSWORDには前述のユーザのパスワードをそれぞれ記述する。
schema.ymlの記述例(MySQLを使用する場合)は下記の通り。
user:
columns:
id: {type: integer, notnull: true, primary: true, autoincrement: true }
mail_address: {type: string(255), notnull: true }
name: {type: string(128), notnull: true, unique: true }
password: {type: string(255), notnull: true }
create_at: {type: timestamp, notnull: true }
image: {type: mediumblob, notnull: true }
enable: {type: boolean }
indexes:
name: {fields: name }
contents:
options:
type: MyISAM
columns:
id: {type: integer, notnull: true, primary: true, autoincrement: true }
name: {type: string(255), notnull: true, unique: true }
description: {type: text, notnull: true }
file_dir: {type: string(255), }
file_name: {type: string(255), notnull: true }
user_id: {type: integer, notnull: true, unsigned: true }
create_at: {type: timestamp, notnull: true }
update_at: {type: timestamp, }
enable: {type: boolean, }
relations:
user: {onDelete: CASCADE, local: user_id, foreign: id, foreignAlias: users }
indexes:
name: {fields: name, type:fulltext }
multiple: {fields: [name,description], type:fulltext }
記述内容について詳細は割愛する。
上記のファイルの編集が完了したら、symfonyプロジェクトディレクトリ配下で下記のコマンドを実行する。
% symfony doctrine:build --all
コマンドを実行するとデータベースの内容がクリアされる旨が表示され、そこで「y」を入力するとモデルファイル(データベースにアクセスするためにsymfony内部で使用されるファイル)が作成され、データベースの再生成が実行される。
ここでエラーメッセージが表示されなければ、当該プロジェクトでデータベースが使用可能となる。
なお、モデルファイルの作成、データベースの生成等はそれぞれ個別に実行する事も可能である。
※詳細についてはsymfonyコマンド及び公式サイトのリファレンスを参照されたい
ちなみに、schema.ymlの内容を書き換えてデータベースを再生成する等して不要になったモデルファイルを削除する場合は下記のコマンドを実行する。
% symfony doctrine:clean-model-files
特殊なインデックスを使用する場合
schema.ymlでは「with parser」等を使用したインデックスの作成等が出来ない。このため、mecabやbigram等のMySQLプラグインを用いたインデックスを作成するためにはMySQL側でSQLを発行してインデックスを別途作成する必要がある。
【掲載日:2010.06.27 / 最終更新日:2011.04.05】
技術情報トップに戻る / トップページに戻る
COPYRIGHT(C)2010-2011 MR.NiNi. All right reserved.
