From myblog : http://noteroad.com/myblog/ 作者:mot
首先你要确定你配置好了Doctrine2,然后在 module/Application/src/Application/Entity( 这里用Application代表模块名 )下面新建你的Entity,一般用你的表名(去掉s).php作为文件名,这里举例的是 staffs (Doctrine 给表命名的规则是 表名词+s)表 ,表的结构是 :
CREATE TABLE IF NOT EXISTS staffs ( id int(8) NOT NULL AUTO_INCREMENT, staff_name varchar(12) NOT NULL, staff_category tinyint(2) NOT NULL, updated_date varchar(10) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
比较简单。而我们的staffs表的Entity应该这样写 :
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Entity Class representing a Post of our Zend Framework 2 Blogging Application
*
* @ORM\Entity
* @ORM\Table(name="staffs")
* @property int $id
* @property string $title
* @property string $text
*/
class Staff {
/**
* Primary Identifier
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var integer
* @access protected
*/
protected $id;
/**
* staff's name
*
* @ORM\Column(type="string")
* @var string
* @access protected
*/
protected $staff_name;
/**
*staff's login password
*
* @ORM\Column(type="text")
* @var string
* @access protected
*/
protected $staff_category;
/**
* password updated date
*
* @ORM\Column(type="text")
* @var string
* @access protected
*/
protected $updated_date;
/**
* Returns the Identifier
*
* @access public
* @return int
*/
public function getid(){
return $this->id;
}
/**
* Sets the Identifier
*
* @param int $id
* @access public
* @return Staff
*/
public function setid($id){
$this->id = $id;
return $this;
}
public function getstaff_name(){
return $this->staff_name;
}
public function setstaff_name($staff_name){
$this->staff_name = $staff_name;
return $this;
}
public function getstaff_category(){
return $this->staff_category;
}
public function setstaff_category($staff_category){
$this->staff_category = $staff_category;
return $this;
}
public function getupdated_date(){
return $this->updated_date;
}
public function setupdated_date($updated_date){
$this->updated_date = $updated_date;
return $this;
}
}
注意!不要忘了 名字空间( namespace ) 和 注释部分的声明( Comment-Annotations ) - (之前漏掉了这些出了错误,都怪我没看手册直接写,还好被Samminds博客的博主提醒了):
类名部分的声明
/** * Entity Class representing a Post of our Zend Framework 2 Blogging Application * * @ORM\Entity * @ORM\Table(name="staffs") * @property int $id * @property string $title * @property string $text */
protected类型的主键以及其它属性的声明:
/**
* Primary Identifier
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var integer
* @access protected
*/
/**
* staff's name
*
* @ORM\Column(type="string")
* @var string
* @access protected
*/
/**
*staff's login password
*
* @ORM\Column(type="text")
* @var string
* @access protected
*/
/**
* password updated date
*
* @ORM\Column(type="text")
* @var string
* @access protected
*/
当然如果为了代码的可读性 每个方法后面最好都加上类似的注释。Doctrine通过这些注释来解析一个Entity,否则会是无法识别的。Entity中不要使用final修饰,也不要从一个类继承过来,这些都是非法的Entity。
posted on
浙公网安备 33010602011771号