在之前的博客中,我们实现并完善了Model类的findOne方法,下面我们来实现其中的其他方法。
先来看findAll方法,这个方法和findOne很相似。
1 | public static function findOne( $condition = null) { $sql = 'select * from ' . static ::tableName(); $params = [];
|
登录后复制
你会发现有findOne和findAll方法很相似,明显可以将公共的部分抽出来,然后我们就多了如下两个方法:
1 | 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 ]; } 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就便成了如下内容:
1 | 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; } 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语句。
1 | 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 ) { |
登录后复制
这样基本的Model就算是暂时完成了,虽然可能还有很多问题和局限,但暂时先这样了,我们之后有机会会一步一步的去完善。
好了,今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。
code:https://github.com/CraryPrimitiveMan/simple-framework/tree/0.7
blog project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework