在之前的博客中,我们实现并完善了Model类的findOne方法,下面我们来实现其中的其他方法。
先来看findAll方法,这个方法和findOne很相似。
public static function findOne($condition = null) { $sql = 'select * from ' . static::tableName(); $params = []; // 判空 if (!empty($condition)) { $sql .= ' where '; $params = array_values($condition); $keys = []; foreach ($condition as $key => $value) { array_push($keys, "$key = ?"); } $sql .= implode(' and ', $keys); } $stmt = static::getDb()->prepare($sql); $rs = $stmt->execute($params); $models = []; if ($rs) { // 直接获取出所有符合条件的 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { if (!empty($row)) { $model = new static(); foreach ($row as $rowKey => $rowValue) { $model->$rowKey = $rowValue; } array_push($models, $model); } } } return null; }
你会发现有findOne和findAll方法很相似,明显可以将公共的部分抽出来,然后我们就多了如下两个方法:
/** * Build a sql where part * @param mixed $condition a set of column values * @return string */ public static function buildWhere($condition, $params = null) { if (is_null($params)) { $params = []; } $where = ''; if (!empty($condition)) { $where .= ' where '; $keys = []; foreach ($condition as $key => $value) { array_push($keys, "$key = ?"); array_push($params, $value); } $where .= implode(' and ', $keys); } return [$where, $params]; } /** * Convert array to model * @param mixed $row the row data from database */ public static function arr2Model($row) { $model = new static(); foreach ($row as $rowKey => $rowValue) { $model->$rowKey = $rowValue; } return $model; }
分别是构建sql中where部分的方法和将查找到的Array转换成Model的方法。大家会奇怪第一个方法中为什么需要params参数和返回值,其实这个为了之后的updateAll方法的使用。其实这个地方跟适合使用引用传值。
这样我们的findOne和findAll就便成了如下内容:
/** * Returns a single model instance by a primary key or an array of column values. * * ```php * // find the first customer whose age is 30 and whose status is 1 * $customer = Customer::findOne(['age' => 30, 'status' => 1]); * ``` * * @param mixed $condition a set of column values * @return static|null Model instance matching the condition, or null if nothing matches. */ public static function findOne($condition = null) { list($where, $params) = static::buildWhere($condition); $sql = 'select * from ' . static::tableName() . $where; $stmt = static::getDb()->prepare($sql); $rs = $stmt->execute($params); if ($rs) { $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!empty($row)) { return static::arr2Model($row); } } return null; } /** * Returns a list of models that match the specified primary key value(s) or a set of column values. * * ```php * // find customers whose age is 30 and whose status is 1 * $customers = Customer::findAll(['age' => 30, 'status' => 1]); * ``` * * @param mixed $condition a set of column values * @return array an array of Model instance, or an empty array if nothing matches. */ public static function findAll($condition = null) { list($where, $params) = static::buildWhere($condition); $sql = 'select * from ' . static::tableName() . $where; $stmt = static::getDb()->prepare($sql); $rs = $stmt->execute($params); $models = []; if ($rs) { $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { if (!empty($row)) { $model = static::arr2Model($row); array_push($models, $model); } } } return $models; }
剩下的updateAll/deleteAll/insert/update和delete方法就不一一详细说明了,直接给出代码。其基本思想都是一致的,都是按照规则拼接SQL语句。
/** * Updates models using the provided attribute values and conditions. * For example, to change the status to be 2 for all customers whose status is 1: * * ~~~ * Customer::updateAll(['status' => 1], ['status' => '2']); * ~~~ * * @param array $attributes attribute values (name-value pairs) to be saved for the model. * @param array $condition the condition that matches the models that should get updated. * An empty condition will match all models. * @return integer the number of rows updated */ public static function updateAll($condition, $attributes) { $sql = 'update ' . static::tableName(); $params = []; if (!empty($attributes)) { $sql .= ' set '; $params = array_values($attributes); $keys = []; foreach ($attributes as $key => $value) { array_push($keys, "$key = ?"); } $sql .= implode(' , ', $keys); } list($where, $params) = static::buildWhere($condition, $params); $sql .= $where; $stmt = static::getDb()->prepare($sql); $execResult = $stmt->execute($params); if ($execResult) { // 获取更新的行数 $execResult = $stmt->rowCount(); } return $execResult; } /** * Deletes models using the provided conditions. * WARNING: If you do not specify any condition, this method will delete ALL rows in the table. * * For example, to delete all customers whose status is 3: * * ~~~ * Customer::deleteAll([status = 3]); * ~~~ * * @param array $condition the condition that matches the models that should get deleted. * An empty condition will match all models. * @return integer the number of rows deleted */ public static function deleteAll($condition) { list($where, $params) = static::buildWhere($condition); $sql = 'delete from ' . static::tableName() . $where; $stmt = static::getDb()->prepare($sql); $execResult = $stmt->execute($params); if ($execResult) { // 获取删除的行数 $execResult = $stmt->rowCount(); } return $execResult; } /** * Inserts the model into the database using the attribute values of this record. * * Usage example: * * ```php * $customer = new Customer; * $customer->name = $name; * $customer->email = $email; * $customer->insert(); * ``` * * @return boolean whether the model is inserted successfully. */ public function insert() { $sql = 'insert into ' . static::tableName(); $params = []; $keys = []; foreach ($this as $key => $value) { array_push($keys, $key); array_push($params, $value); } // 构建由?组成的数组,其个数与参数相等数相同 $holders = array_fill(0, count($keys), '?'); $sql .= ' (' . implode(' , ', $keys) . ') values ( ' . implode(' , ', $holders) . ')'; $stmt = static::getDb()->prepare($sql); $execResult = $stmt->execute($params); // 将一些自增值赋回Model中 $primaryKeys = static::primaryKey(); foreach ($primaryKeys as $name) { // Get the primary key $lastId = static::getDb()->lastInsertId($name); $this->$name = (int) $lastId; } return $execResult; } /** * Saves the changes to this model into the database. * * Usage example: * * ```php * $customer = Customer::findOne(['id' => $id]); * $customer->name = $name; * $customer->email = $email; * $customer->update(); * ``` * * @return integer|boolean the number of rows affected. * Note that it is possible that the number of rows affected is 0, even though the * update execution is successful. */ public function update() { $primaryKeys = static::primaryKey(); $condition = []; foreach ($primaryKeys as $name) { $condition[$name] = isset($this->$name) ? $this->$name : null; } $attributes = []; foreach ($this as $key => $value) { if (!in_array($key, $primaryKeys, true)) { $attributes[$key] = $value; } } return static::updateAll($condition, $attributes) !== false; } /** * Deletes the model from the database. * * @return integer|boolean the number of rows deleted. * Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful. */ public function delete() { $primaryKeys = static::primaryKey(); $condition = []; foreach ($primaryKeys as $name) { $condition[$name] = isset($this->$name) ? $this->$name : null; } return static::deleteAll($condition) !== false; }
这样基本的Model就算是暂时完成了,虽然可能还有很多问题和局限,但暂时先这样了,我们之后有机会会一步一步的去完善。
好了,今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。
code:https://github.com/CraryPrimitiveMan/simple-framework/tree/0.7
blog project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework
相关文章推荐
• 什么是php-fpm?如何进行优化来提升性能?• 实例详解怎么用PHP实现简易的MVC框架• 消息队列RabbitMQ入门与PHP实例详解• webservice有关问题,soap有关问题,响应有关问题-求大神!大神在哪• 看不懂这两行代码啊 请教下独孤九贱(3)_JavaScript视频教程
javascript是运行在浏览器上的脚本语言,连续多年,被评为全球最受欢迎的编程语言。是前端开发必备三大法器中,最具杀伤力。如果前端开发是降龙十八掌,好么javascript就是第18掌:亢龙有悔。没有它,你的前端生涯是不完整的。《php.cn独孤九贱(3)-JavaScript视频教程》课程特色:php中文网原创幽默段子系列课程,以恶搞,段子为主题风格的php视频教程!轻松的教学风格,简短的教学模式,让同学们在不知不觉中,学会了javascript知识。
JavaScript教程124058次播放
独孤九贱(6)_jQuery视频教程
jQuery是一个快速、简洁的JavaScript框架。设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。 核心特性可以总结为:具有独特的链式语法和短小清晰的多功能接口;具有高效灵活的css选择器,并且可对CSS选择器进行扩展;拥有便捷的插件扩展机制和丰富的插件。兼容各种主流浏览器,如IE 6.0+、FF 1.5+、Safari 2.0+、Opera 9.0+等,是全球最流行的前端开发框架之一。PHP中文网根据最新版本,独家录制jQuery最新视频教程,回馈PHP中文网的新老用户。
jQuery教程102565次播放
jQuery与Ajax基础与实战
jQuery是最流行的JS函数库,封装了许多实用的功能,其中最引人入胜的就是Ajax。 jQuery中的Ajax操作,语法简单,操作方便,使Ajax从未如此轻松,前端人员从此不再为与服务器异步交互而发愁,本套课程,精选了最常用的几个方法,从基本的语法到每个参数,再到具体实例进行了全面的讲解。
AJAX教程3927次播放
Git教程(60分钟全程无废话版)
Git 是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目。 Git 是 Linus Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本控制软件。 Git 与常用的版本控制工具 CVS, Subversion 等不同,它采用了分布式版本库的方式,不必服务器端软件支持
JavaScript教程3258次播放