Heim Backend-Entwicklung PHP-Tutorial 构建自己的PHP框架实现Model类(3)

构建自己的PHP框架实现Model类(3)

Jun 23, 2016 pm 01:15 PM

在之前的博客中,我们实现并完善了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;    }
Nach dem Login kopieren

你会发现有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;    }
Nach dem Login kopieren

分别是构建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;    }
Nach dem Login kopieren

剩下的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;    }
Nach dem Login kopieren

这样基本的Model就算是暂时完成了,虽然可能还有很多问题和局限,但暂时先这样了,我们之后有机会会一步一步的去完善。

好了,今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。

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

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

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
2 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Repo: Wie man Teamkollegen wiederbelebt
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Abenteuer: Wie man riesige Samen bekommt
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) 11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) Mar 03, 2025 am 10:49 AM

Lange URLs, die oft mit Schlüsselwörtern und Tracking -Parametern überfüllt sind, können Besucher abschrecken. Ein URL -Verkürzungsskript bietet eine Lösung, die präzise Links erstellt, die ideal für soziale Medien und andere Plattformen sind. Diese Skripte sind für einzelne Websites a wertvoll

Einführung in die Instagram -API Einführung in die Instagram -API Mar 02, 2025 am 09:32 AM

Nach seiner hochkarätigen Akquisition durch Facebook im Jahr 2012 nahm Instagram zwei APIs für den Einsatz von Drittanbietern ein. Dies sind die Instagram -Graph -API und die Instagram Basic Display -API. Ein Entwickler, der eine App erstellt, die Informationen von a benötigt

Arbeiten mit Flash -Sitzungsdaten in Laravel Arbeiten mit Flash -Sitzungsdaten in Laravel Mar 12, 2025 pm 05:08 PM

Laravel vereinfacht die Behandlung von temporären Sitzungsdaten mithilfe seiner intuitiven Flash -Methoden. Dies ist perfekt zum Anzeigen von kurzen Nachrichten, Warnungen oder Benachrichtigungen in Ihrer Anwendung. Die Daten bestehen nur für die nachfolgende Anfrage standardmäßig: $ Anfrage-

Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Mar 12, 2025 pm 05:09 PM

Laravel bietet eine kurze HTTP -Antwortsimulationssyntax und vereinfache HTTP -Interaktionstests. Dieser Ansatz reduziert die Code -Redundanz erheblich, während Ihre Testsimulation intuitiver wird. Die grundlegende Implementierung bietet eine Vielzahl von Verknüpfungen zum Antworttyp: Verwenden Sie Illuminate \ Support \ facades \ http; Http :: fake ([ 'Google.com' => 'Hallo Welt',, 'github.com' => ['foo' => 'bar'], 'Forge.laravel.com' =>

Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Mar 04, 2025 am 09:33 AM

Dies ist der zweite und letzte Teil der Serie zum Aufbau einer Reaktionsanwendung mit einem Laravel-Back-End. Im ersten Teil der Serie haben wir eine erholsame API erstellt, die Laravel für eine grundlegende Produktlistenanwendung unter Verwendung von Laravel erstellt hat. In diesem Tutorial werden wir Dev sein

Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Mar 14, 2025 am 11:42 AM

Die PHP Client -URL -Erweiterung (CURL) ist ein leistungsstarkes Tool für Entwickler, das eine nahtlose Interaktion mit Remote -Servern und REST -APIs ermöglicht. Durch die Nutzung von Libcurl, einer angesehenen Bibliothek mit Multi-Protokoll-Dateien, erleichtert PHP Curl effiziente Execu

12 Beste PHP -Chat -Skripte auf Codecanyon 12 Beste PHP -Chat -Skripte auf Codecanyon Mar 13, 2025 pm 12:08 PM

Möchten Sie den dringlichsten Problemen Ihrer Kunden in Echtzeit und Sofortlösungen anbieten? Mit Live-Chat können Sie Echtzeitgespräche mit Kunden führen und ihre Probleme sofort lösen. Sie ermöglichen es Ihnen, Ihrem Brauch einen schnelleren Service zu bieten

Ankündigung von 2025 PHP Situation Survey Ankündigung von 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

Die 2025 PHP Landscape Survey untersucht die aktuellen PHP -Entwicklungstrends. Es untersucht Framework -Nutzung, Bereitstellungsmethoden und Herausforderungen, die darauf abzielen, Entwicklern und Unternehmen Einblicke zu geben. Die Umfrage erwartet das Wachstum der modernen PHP -Versio

See all articles