php-与数据库对应实体类的命名
时间:2011-03-08 来源:bobolive
数据库建表时,我们有时会这样命名"resource_id" 来表示这是个resource表里面的"id"字段。当表名比较长时我们可能会这样"resource_ref"表示资源影射表。这样的表通常有外键,很可能就是我们在开头命名的"resource_id"。这时候字段名可能就变成"resource_ref_resource_id"。OK,这样稍微比一长串字符串的命名好认一些。但做实体的时候,你应该不要做一模一样的命名。
View Code1 <?php
2 class Zwb_Models_Entity_ResourceRef {
3 private $_id;
4 private $_roleId;
5 private $_resourceId;
6
7 public function get($key){
8 return $this->{'_'.$key};
9 }
10
11 public function set($key,$val){
12 $this->{'_'.$key} = $val;
13 }
14 /**
15 * @return the $id
16 */
17 public function getId() {
18 return $this->_id;
19 }
20
21 /**
22 * @return the $roleid
23 */
24 public function getRoleid() {
25 return $this->_roleId;
26 }
27
28 /**
29 * @return the $resourceid
30 */
31 public function getResourceid() {
32 return $this->_resourceId;
33 }
34
35 /**
36 * @param $id the $id to set
37 */
38 public function setId($id) {
39 $this->_id = $id;
40 }
41
42 /**
43 * @param $roleid the $roleid to set
44 */
45 public function setRoleid($roleid) {
46 $this->_roleId = $roleid;
47 }
48
49 /**
50 * @param $resourceid the $resourceid to set
51 */
52 public function setResourceid($resourceid) {
53 $this->_resourceId = $resourceid;
54 }
55
56
57 }
对应起来可以这样
<?php
class Zwb_Functions_CapitalToUnderline {
public static function capitalToUnderline($str) {
$temp = preg_split("/(?=[A-Z])/", $str);
if(count($temp)>1)
{
$arr = implode('_', $temp);
return strtolower($arr);
}
return $str;
}
}
public function fetchAll($options) {
$table = Zwb_Functions_CapitalToUnderline::capitalToUnderline($options['table']);
$db = Zwb_Models_DbEntry::getInstance()->getdb();
$objects = array();
$result = $db->fetchAll("SELECT * FROM ".$table);
$objectName = 'Zwb_Models_Entity_'.ucfirst($table);
foreach($result as $row)
{
$object = new $objectName();
$objectArray = (array) $object;
foreach($objectArray as $key => $val)
{
$key = trim(substr($key, strlen($objectName)+3));//类成员为私有,转换时要去除类名
$tablekey = Zwb_Functions_CapitalToUnderline::capitalToUnderline($key);
$object->set($key, $row[$table.'_'.$tablekey]);
}
$objects[] = $object;
}
return $objects;
}
相关阅读 更多 +