Building your own PHP framework-Implementing Model Class 3

Source: Internet
Author: User
Tags findone php framework rowcount
In our previous blog, we implemented and perfected the FindOne method of the model class, and we implemented the other methods below.

First look at the FindAll method, which is similar to FindOne.

 PublicStaticfunctionFindOne($condition=NULL){$sql=' select * from '.Static:: TableName();$params=[];//Emptyif(!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){//Direct access to all eligible$rows=$stmt->fetchall(PDO::Fetch_assoc);foreach($rows as$row){if(!Empty($row)){$model=NewStatic();foreach($row as$rowKey=$rowValue){$model-$rowKey=$rowValue;}Array_push($models,$model);}            }        }returnNULL;}

You will find that there are findone and FindAll methods that are very similar, and obviously can be pulled out of the public sector, and then we have the following two methods:

/*** Build A SQL where part     * @paramMixed$condition A set of column values     * @returnstring     */ PublicStaticfunctionBuildwhere($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     * @paramMixed$row the row data from database     */ PublicStaticfunctionArr2model($row){$model=NewStatic();foreach($row as$rowKey=$rowValue){$model-$rowKey=$rowValue;}return$model;}

The method for constructing the where part of SQL and the method of converting the found array into model are respectively. Everyone will wonder why the first method requires the params parameter and the return value, in fact, for the later use of the UpdateAll method. In fact this place is suitable for use with reference values.

In this way our findone and FindAll handy become the following:

/*** Returns A single model instance by a primary key or an array of column values.     ** "PHP "*//Find the first customer whose age is a and whose status is 1* $customer = Customer::findone ([' age ' = +, ' status ' + 1]);     * ```     *     * @paramMixed$condition A set of column values     * @returnStatic|null Model Instance matching the condition, or null if nothing matches.     */ PublicStaticfunctionFindOne($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)){returnStatic:: Arr2model($row);}        }returnNULL;}/*** 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 and whose status is 1* $customers = Customer::findall ([' age ' = +, ' status ' + 1]);     * ```     *     * @paramMixed$condition A set of column values     * @returnarray An array of Model instance, or a empty array if nothing matches.     */ PublicStaticfunctionFindAll($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;}

The rest of the updateall/deleteall/insert/update and delete methods are not explained in detail, and the code is given directly. The basic ideas are consistent, and are all based on the rules to splice SQL statements.

/*** Updates models using the provided attribute values and conditions.* For example, the ' to ' change the ' status ' to ' 2 for all customers whose status ' is 1:     *     * ~~~* Customer::updateall ([' Status ' = 1], [' status ' = ' 2 ']);     * ~~~     *     * @paramArray$attributes attribute values (Name-value pairs) to being saved for the model.     * @paramArray$condition The condition that matches the models, that should get updated.* An empty condition would match all models.     * @returnInteger the number of rows updated     */ PublicStaticfunctionUpdateAll($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){//Gets the number of updated rows$execResult=$stmt->rowcount();}return$execResult;}/*** Deletes models using the provided conditions.* warning:if You don't specify any condition, this method would delete all rows in the table.     ** For example, to-delete all customers whose status is 3:     *     * ~~~* Customer::d eleteall ([status = 3]);     * ~~~     *     * @paramArray$condition The condition that matches the models, that should get deleted.* An empty condition would match all models.     * @returnInteger the number of rows deleted     */ PublicStaticfunctionDeleteAll($condition){List($where,$params)=Static:: Buildwhere($condition);$sql=' Delete from '.Static:: TableName().$where;$stmt=Static:: Getdb()->prepare($sql);$execResult=$stmt->execute($params);if($execResult){//Gets the number of deleted rows$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 ();     * ```     *     * @returnThe Boolean whether the model is inserted successfully.     */ PublicfunctionInsert(){$sql=' INSERT INTO '.Static:: TableName();$params=[];$keys=[];foreach($this as$key=$value){Array_push($keys,$key);Array_push($params,$value);}//build by? An array of the same number as the parameter equality$holders=Array_fill(0,Count($keys),'?');$sql.=' ('.implode(' , ',$keys).') VALUES ('.implode(' , ',$holders).')';$stmt=Static:: Getdb()->prepare($sql);$execResult=$stmt->execute($params);//Assign some self-added value back to model$primaryKeys=Static::p Rimarykey();foreach($primaryKeys as$name){//Get the primary key$lastId=Static:: Getdb()->lastinsertid($name);$this-$name=(int)$lastId;}return$execResult;}/*** Saves The changes to the the database.     ** Usage Example:     ** "PHP "* $customer = Customer::findone ([' id ' = ' = $id]);* $customer->name = $name;* $customer->email = $email;* $customer->update ();     * ```     *     * @returnInteger|boolean the number of rows affected.* Note that it was possible that number of rows affected is 0, even though the* Update execution is successful.     */ PublicfunctionUpdate(){$primaryKeys=Static::p Rimarykey();$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;}        }returnStatic:: UpdateAll($condition,$attributes)!==false;}/*** Deletes the model from the database.     *     * @returnInteger|boolean the number of rows deleted.* Note that it was possible that number of rows deleted are 0, even though the deletion execution is successfu L.     */ PublicfunctionDelete(){$primaryKeys=Static::p Rimarykey();$condition=[];foreach($primaryKeys as$name){$condition[$name]=isset($this-$name)?$this-$name:NULL;}returnStatic::d Eleteall($condition)!==false;}

This basic model, even if it is temporarily completed, although there may be a lot of problems and limitations, but for the time being, we will have the opportunity to improve step-by-step.

All right, let's get here today. Project content and blog content will also be put on GitHub, welcome suggestions.

code:https://github.com/craryprimitiveman/simple-framework/tree/0.7

Blog Project:https://github.com/craryprimitiveman/create-your-own-php-framework

The above describes the construction of their own PHP framework-the implementation of model Class 3, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.