博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Codeigniter:如何写一个好的Model
阅读量:7240 次
发布时间:2019-06-29

本文共 9259 字,大约阅读时间需要 30 分钟。

本文是关于在Code Igniter PHP MVC框架中如何编写Model方法。
CRUD 方法
CRUD 是Create, Retrieve, Update, and Delete的缩写. 这些是最基本的数据源交互方法。

如:

Create[增] – 添加一个用户账号
Retrieve[查] – 获取一个产品列表

Update[改] – 修改用户密码或产品名称

Delete[删] – 删除一个用户或产品

编写model时,一般首先会创建CRUD方法。如果你正在编写用户身份验证(登陆,注销,忘记密码,激活帐户),你还需要能添加、修改和删除用户的功能。

如:

function AddUser() function UpdateUser() function DeleteUser() function GetUsers()

 

这四个方法可以处理大部分情况。与创建一个model方法"GetActiveUsers” 相比,我们只需要在GetUsers方法中创建一个参数来获取指定用户状态的结果集,就可以达到同样目的。更多如下…

以数组作参数

一般,方法的参数写法如以下方式:

function AddUser($insertData) function UpdateUser($userId, $updateData) function DeleteUser($userId) function GetUsers($limit, $offset)

 

这种写法的缺点是我们可能需要很多参数,甚至不得不创建同一个方法的不同参数版本。

如:

function GetUsers($limit, $offset, $status)

我们可能还需要GetUser($userId)方法。这使我们创建了同一个方法的多个版本。 以GetUsers为例,如果我们修改信息的返回方式,就得改动两处地方,GetUser和GetUsers。

为了克服这些缺点,建议使用数组作为参数,如下:

function AddUser($options = array()) function UpdateUser($options = array()) function DeleteUser($options = array()) function GetUsers($options = array())

在这之前,我们可能需要使用GetUsers(5, 5, ‘active’)返回一组用户列表,现在只需要GetUsers(array(‘limit’ => 5, ‘offset’ => 5, ‘status’ => 'active’);

以数组作为参数,参数内的选项可以任意顺序输入,甚至完全忽略参数。如果你需要添加功能性参数,仅需要修改该model方法本身,而不是到处修改代码。

实用方法

这里我们提供几个辅助方法,提高我们创建的方法的健壮性。 即,设定字段必需和字段默认值。如,添加一个用户时,userEmail字段是必填的。为此我们创建了 ‘required’ 方法。

/** * _required method returns false if the $data array does not contain all of the keys * assigned by the $required array. * * @param array $required * @param array $data * @return bool */ function _required($required, $data) {
foreach($required as $field) if(!isset($data[$field])) return false; return true; }

在'AddUser’ 例子中,我们的代码可能如下:

/** * AddUser method creates a record in the users table. * * Option: Values * -------------- * userEmail            (required) * userPassword * userName * userStatus        active(default), inactive, deleted * * @param array $options */ function AddUser($options = array()) {
// required values if(!$this->_required(array('userEmail'), $options)) return false; // At this point we know that the key 'userEmail' exists in the $options array. }

现在,如果'userEmail’字段没有在数组参数内输入,我们的AddUser方法将返回false。

新创建的用户默认是 ‘active’激活的。 如果我们想要创建一个非激活的用户,设定 ‘userStatus’ 参数的值为inactive。现在我们不想要每次都要申明用户为 ‘active’,把他设定为默认值即可。

  'default’ 方法:

/** * _default method combines the options array with a set of defaults giving the values * in the options array priority. * * @param array $defaults * @param array $options * @return array */ function _default($defaults, $options) {
return array_merge($defaults, $options); }

如果在数组参数内指定与默认值相同的字段,则会覆盖默认值。

在AddUser中使用 ‘default’ 方法:

/** * AddUser method creates a record in the users table. * * Option: Values * -------------- * userEmail            (required) * userPassword * userName * userStatus        active(default), inactive, deleted * * @param array $options */ function AddUser($options = array()) {
// required values if(!$this->_required(array('userEmail'), $options)) return false; // default values $options = $this->_default(array('userStatus' => 'active'), $options); }

如果$options数组存在 ‘userStatus’ 字段,则覆盖默认值,否则使用默认值 ‘active’。

这些辅助方法占用很少的代码,可以使你的代码更加健壮。

Active Record

注:与数据库相关的设计模式

许多数据库(MySQL,Oracle,Microsoft SQL,PostgreSQL,etc)使用SQL语法,却有稍微有点不同。一个Active Record类允许你比较抽象的创建一条查询,它可以运行在该类支持的所有数据库上,而不必关注多个数据库sql语法在细节上的不同。

Code Igniter Active Record 可能像以下这样:

$this->db->where('userStatus''active');
$this->db->get('users');

这两条命令将创建和执行查询: “select * from users where userStatus = ‘active’”

一个完整的模型类

以下例子包含增删查改方法。

/** * AddUser method creates a record in the users table. * * Option: Values * -------------- * userEmail            (required) * userPassword * userName * userStatus        active(default), inactive, deleted * * @param array $options */ function AddUser($options = array()) {
// required values if(!$this->_required(array('userEmail'), $options)) return false; // default values $options = $this->_default(array('userStatus' => 'active'), $options); // qualification (make sure that // we're not allowing the site to insert data that it shouldn't) $qualificationArray = array('userEmail', 'userName', 'userStatus'); foreach($qualificationArray as $qualifier) {
if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]); } // MD5 the password if it is set if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword'])); // Execute the query $this->db->insert('users'); // Return the ID of the inserted row, // or false if the row could not be inserted return $this->db->insert_id(); } /** * UpdateUser method alters a record in the users table. * * Option: Values * -------------- * userId the ID of the user record that will be updated * userEmail * userPassword * userName * userStatus active(default), inactive, deleted * * @param array $options * @return int affected_rows() */ function UpdateUser($options = array()) {
// required values if(!$this->_required(array('userId'), $options)) return false; // qualification (make sure that // we're not allowing the site to update data that it shouldn't) $qualificationArray = array('userEmail', 'userName', 'userStatus'); foreach($qualificationArray as $qualifier) {
if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]); } $this->db->where('userId', $options['userId']); // MD5 the password if it is set if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword'])); // Execute the query $this->db->update('users'); // Return the number of rows updated, or false if the row could not be inserted return $this->db->affected_rows(); } /** * GetUsers method returns an array of qualified user record objects * * Option: Values * -------------- * userId * userEmail * userStatus * limit limits the number of returned records * offset how many records to bypass before returning a record (limit required) * sortBy determines which column the sort takes place * sortDirection (asc, desc) sort ascending or descending (sortBy required) * * Returns (array of objects) * -------------------------- * userId * userEmail * userName * userStatus * * @param array $options * @return array result() */ function GetUsers($options = array()) {
// default values $options = $this->_default(array('sortDirection' => 'asc'), $options); // Add where clauses to query $qualificationArray = array('userId', 'userEmail', 'userStatus'); foreach($qualificationArray as $qualifier) {
if(isset($options[$qualifier])) $this->db->where($qualifier, $options[$qualifier]); } // If limit / offset are declared (usually for pagination) // then we need to take them into account if(isset($options['limit']) && isset($options['offset'])) $this->db->limit($options['limit'], $options['offset']); else if(isset($options['limit'])) $this->db->limit($options['limit']); // sort if(isset($options['sortBy'])) $this->db->order_by($options['sortBy'], $options['sortDirection']); $query = $this->db->get('users'); if($query->num_rows() == 0) return false; if(isset($options['userId']) && isset($options['userEmail'])) {
// If we know that we're returning a singular record, // then let's just return the object return $query->row(0); } else {
// If we could be returning any number of records // then we'll need to do so as an array of objects return $query->result(); } } /** * DeleteUser method removes a record from the users table * * @param array $options */ function DeleteUser($options = array()) {
// required values if(!$this->_required(array('userId'), $options)) return false; $this->db->where('userId', $options['userId']); $this->db->delete('users'); }

以下这些例子是如何调用该模型类的方法。

添加一个用户

$userId = $this->user_model->AddUser($_POST); if($userId)     echo "The user you have created has been added successfully with ID #" . $userId; else     echo "There was an error adding your user.";

修改一个用户

if($this->user_model->UpdateUser(array('userId' => 3,                          'userName' => 'Shawn',                         'userEmail' => 'not telling')))     // The user has been successfully updated else     // The user was not updated

用户身份验证(查找单一用户)

$user = $this->user_model->GetUsers(array('userEmail' => $userEmail,                          'userPassword' => md5($userPassword),                         'userStatus' => 'active')); if($user)     // Log the user in else     // Sorry, your user / password combination isn't correct.

查找一组用户

$users = $this->user_model->GetUsers(array('userStatus' => 'active')); if($users) {
echo "Active Users
"; foreach($users as $user) {
echo $user->userName . "
"; } } else {
echo "There are no active users."; }

删除一个用户

$this->user_model->DeleteUser(array('userId' => $userId));

 

如果你有任何建议和意见,欢迎探讨和指教。

 

作者:
出处:
如何联系我:【万里虎】www.bravetiger.cn 【QQ】3396726884 (咨询问题100元起,帮助解决问题500元起) 【博客】http://www.cnblogs.com/kenshinobiy/
你可能感兴趣的文章
Linux命令:MySQL系列之九--MySQL隔离级别及设置
查看>>
WordPress匿名投稿插件:DX-Contribute(WP我要投稿,我要爆料)
查看>>
BBSSDK数据同步存储原理
查看>>
avascript获取网页中指定节点的父节点、子节点的方法小结
查看>>
RedHat 7配置HAProxy实现Web负载均衡
查看>>
rsync详解
查看>>
OSPF邻接关系建立
查看>>
液/气双通道散热数据中心团体标准正式启动编制
查看>>
nginx重定向设置
查看>>
使用Mkfifo和Script命令实现在Linux平台上实时演示
查看>>
dns资源记录类型等
查看>>
cacti-0.8.7g的安装
查看>>
如何做到人均利润超过阿里巴巴?7-eleven的互联网思维
查看>>
Linux系统使用普通命令删除不掉的文件处理方法
查看>>
算法学习之路|人口普查
查看>>
canon iPF 系列保养墨盒清零方法
查看>>
kubernetes1.9离线部署
查看>>
Emulating Neural Synapses through AI
查看>>
Oracle in与exists语句
查看>>
pt-kill
查看>>