我正在使用Zend Framework并尝试使用"快速入门"指南来对付我正在制作的网站以了解该流程的工作原理.如果这个答案显而易见,请原谅我,希望有经验的人可以对此有所了解.
我有三个数据库表:
CREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `email` varchar(255) NOT NULL, `username` varchar(255) NOT NULL default '', `first` varchar(128) NOT NULL default '', `last` varchar(128) NOT NULL default '', `gender` enum('M','F') default NULL, `birthyear` year(4) default NULL, `postal` varchar(16) default NULL, `auth_method` enum('Default','OpenID','Facebook','Disabled') NOT NULL default 'Default', PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 CREATE TABLE `user_password` ( `user_id` int(11) NOT NULL, `password` varchar(16) NOT NULL default '', PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 CREATE TABLE `user_metadata` ( `user_id` int(11) NOT NULL default '0', `signup_date` datetime default NULL, `signup_ip` varchar(15) default NULL, `last_login_date` datetime default NULL, `last_login_ip` varchar(15) default NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1
我想创建一个在某些情况下使用所有三个表的用户模型.例如,如果/当需要元数据时,访问元数据表.仅当设置了"Default"auth_method时才访问user_password表.我可能稍后会添加一个配置文件表,我希望能够从用户模型访问.
使用ZF的最佳方法是什么?为什么?
class Users extends Zend_Db_Table_Abstract { protected $_name = 'users'; protected $_rowClass = 'User'; protected $_dependentTables = array ('UserMetadata', 'UserPassword'); ... class UserMetadata extends Zend_Db_Table_Abstract { protected $_name = 'user_metadata'; protected $_referenceMap = array ( 'Users'=> array ( 'columns'=>'user_id', 'refTableClass'=>'Users', 'refColumns'=>'id' ) ); ... class UserPassword extends Zend_Db_Table_Abstract { protected $_name = 'user_password'; protected $_referenceMap = array ( 'Users'=> array ( 'columns'=>'user_id', 'refTableClass'=>'Users', 'refColumns'=>'id' ) );
获取数据:
$id = //get your user id from somewhere $users = new Users(); $user = $users->fetchRow('id=?', $id); if ($user->authMethod == 0) { $metadata = $user->findDependentRowset('UserMetadata')->current(); }
要么
$user = $users->fetchRow($users->select() ->where('gender=?, 'M') ->order('email ASC');
...等
插入数据:
$newRow = $users->fetchNew(); $newRow->email = me@domain.com; $newRow->save();
要么
$users = new Users(); $data = array('email' => 'me@domain.com', 'firstname' => 'Me'); $users->insert($data);
更新:
$user->email = 'me@domain.org'; $user->save();
删除一行:
$user->delete();
使用交易:
$db->beginTransaction(); $db->commit(); $db->rollback();
等......这些都在ZF手册中!