Doctrine は, PHPのORM (Object-relational mapping : オブジェクト指向言語におけるオブジェクトと、MySQLやPostgreSQLの様な、リレーショナルデータベースにおけるレコードとを対照させるもの) で、Symfonyで利用されている。
詳しくは、Databases and Doctrine ("The Model")を参照してください。
データベースの情報を設定
まず、データベースに接続するためには, app/config/parameters.ini でホストなどを指定する。[parameters]
database_driver="pdo_mysql"
database_host="localhost"
database_name="hoge"
database_user="moge"
database_password="piyo"
以下のコマンドを叩けば、app/config/parameters.ini の情報に基づいてデータベースを作成してくれる。
php app/console doctrine:database:create
Entity Class の作成
エンティティを、src/Acme/StoreBundle/Entity/ のような場所 (〇〇Bundle/Entity下) に作成する。(このクラス自体は、データを格納するだけ)まず、以下のコマンドを実行する。
php app/console doctrine:generate:entity --entity="AcmeStoreBundle:Product" --fields="name:string(255) price:float description:text"
すると、ORM情報をアノテーションとして設定されているエンティティクラスが作成される (以下)。
また、Getter と Setter も用意してくれます。
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\DemoBundle\Entity\Product
*
* @ORM\Table()
* @ORM\Entity
*/
class Product
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $name
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var float $price
*
* @ORM\Column(name="price", type="float")
*/
private $price;
/**
* @var text $description
*
* @ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* @param float $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* Get price
*
* @return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set description
*
* @param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* @return text
*/
public function getDescription()
{
return $this->description;
}
}
ORM情報をYAML等のコンフィグファイルで設定したい場合は、--format=yml のオプションを加えることで可能。(その場合のコンフィグファイルは、src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.yml となる)
ちなみに、SQLのキーワードとなってる名前をフィールドにつけようとすると、エラーとなるらしい。その場合は、
/** @Column(name="`number`", type="integer") */ private $number;のようにエスケープが必要らしいです。(Reserved SQL keywords documentation より)
テーブル/スキーマの作成
次の以下のコマンドを実行すれば、自動的にテーブル/スキーマの作成を行なってくれる。php app/console doctrine:schema:update --force
とりあえず、今回はココまでっ!!



0 コメント:
コメントを投稿