Build your own PHP framework to implement the Model class (3)-php Tutorial

Source: Internet
Author: User
Tags findone
Build your own PHP framework to implement the Model class (3) in the previous blog, we have implemented and improved the findOne method of the Model class. next we will implement other methods.

Let's look at the findAll method. this method is similar to findOne.

Public static function findOne ($ condition = null) {$ SQL = 'select * from'. static: tableName (); $ params = []; // empty 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) {// get all the qualified $ 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 ;}

You will find that the findOne and findAll methods are very similar. Obviously, you can extract the public part. then we have two more methods:

    /** * 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;    }

They are the method for building the where part of the SQL statement and converting the searched Array to the Model. You may wonder why params parameters and return values are required in the first method. In fact, this is the use of the updateAll method later. In fact, this part is suitable for using reference to transmit values.

In this way, our findOne and findAll become the following content:

    /** * 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;    }

The remaining updateAll/deleteAll/insert/update and delete methods are not described in detail, and the code is provided directly. The basic idea is the same. all SQL statements are spliced according to rules.

/*** Updates models using the provided attribute values and conditions. * For example, to change the status to be 2 for all MERS 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 shocould 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) {// Obtain the number of updated rows $ execResult = $ stmt-> rowCount ();} return $ execResult;}/*** Deletes models using the provided conditions. * WARNING: If you do not specify any condition, this method wil L delete ALL rows in the table. ** For example, to delete all MERS whose status is 3 :**~~~ * Customer: deleteAll ([status = 3]); * ~~~ ** @ Param array $ condition the condition that matches the models that shocould 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) {// get 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 (); * "** @ return boolean whether the model is inserted successfully. */pub Lic function insert () {$ SQL = 'Insert '. static: tableName (); $ params = []; $ keys = []; foreach ($ this as $ key = >$ value) {array_push ($ keys, $ key); array_push ($ params, $ value);} // created? The number of elements in an array is the same as the number of equal parameters $ holders = array_fill (0, count ($ keys ),'? '); $ SQL. = '('. implode (',', $ keys ). ') values ('. implode (',', $ holders ). ')'; $ stmt = static: getDb ()-> prepare ($ SQL); $ execResult = $ stmt-> execute ($ params ); // assign some auto-increment values back to $ primaryKeys = static: primaryKey (); foreach ($ primaryKeys as $ name) {// Get the primary key $ lastId = static:: getDb ()-> lastInsertId ($ name); $ this-> $ name = (int) $ lastId;} return $ execResult;}/*** Saves the c Hanges 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 ;}

Even if the basic Model is completed for the time being, although there may be many problems and limitations, this is the first thing to do. we will then have the opportunity to complete it step by step.

Now, we will be here today. The project content and blog content will also be put on Github. You are welcome to give suggestions.

Code: https://github.com/CraryPrimitiveMan/simple-framework/tree/0.7

Blog project: https://github.com/CraryPrimitiveMan/create-your-own-php-framework

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.