Hello Doctrine2
I. 初始化环境1. 下载DoctrineORM-2.0.0-BETA1.tgz
2. include_path设定
解压缩后将DoctrineORM-2.0.0目录下的Doctrine 放到include_path涉及的目录,放好后目录结构如下:
http://dl.iteye.com/upload/attachment/246393/a98381d9-5143-39b5-ac06-d73fc5035cc1.jpg
3. 建立项目布局
将tools\sandbox目录下的index.php复制到自己的项目目录下作为doctrine2的开端是一个比较好的实践。复制过来需要修改该文件的两处:
1).将
require '../../lib/Doctrine/Common/ClassLoader.php';
修改为
require 'Doctrine/Common/ClassLoader.php';
(因为前面已经将doctrine2的包放到了include_path涉及的目录)
2).将下面代码
$user = new User;$address = new Address;
注释掉
4. 运行Index.php
php index.php 输出 Hello World!
II. 数据库操作
1. 修改数据库连接
index.php原有一处
$connectionOptions = array( 'driver' => 'pdo_sqlite', 'path' => 'database.sqlite');默认链接sqlite数据库,但是如果你的服务器没有enable它,或者向连接到mysql数据,请修改为:
$connectionOptions = array('dbname' => 'mydb','user' => 'root','password' => '','host' => '127.0.0.1','driver' => 'pdo_mysql',);
(具体参数根据你的服务器配置做相应修改)
2. 建立实体文件到index.php的Entities目录下
这里以User为例:
<?phpnamespace Entities;/** @Entity @Table(name="users") */class User {/** * @Id @Column(type="integer") * @GeneratedValue(strategy="AUTO") */private $user_id;/** @Column(type="string", length=50) */private $name;private $address;public function getUserId(){ return $this->user_id;}public function getName(){ return $this->name;}public function setName($name){ $this->name = $name;}}
3. 建立数据库schema
CREATE TABLE `users` (`name` varchar(32) default NULL,`user_id` int(11) NOT NULL auto_increment,PRIMARY KEY(`user_id`));
4. 修改index.php.
1). 在index.php头部use前面建立的实体类
use Entities\User; //实际默认已经引用了该类.
2) 在index.php末尾增加如下代码
$user = new User;$user->setName('Allen');$em->persist($user);$em->flush();
5. 重新运行index.php
查看数据库,看到如下结果
mysql> select * from users;+-------+---------+| name| user_id |+-------+---------+| Allen | 1 |+-------+---------+1 row in set (0.00 sec)
附件是项目代码,请参考
页:
[1]