ホームページ バックエンド開発 PHPチュートリアル 独自の 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;    }
ログイン後にコピー

findOne メソッドと findAll メソッドが非常に似ていることがわかります。共通部分を抽出できることは明らかであり、さらに次の 2 つのメソッドがあります。

    /** * 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 部分をそれぞれ構築して、見つかった配列をモデルに変換します。なぜ最初のメソッドで 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 メソッドについては、1 つずつ詳しく説明せず、コードを直接示します。基本的な考え方は同じで、すべてルールに従って 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;    }
ログイン後にコピー

この基本的なモデルはまだ多くの問題や制限があるかもしれませんが、現時点ではこれだけです。機会があれば段階的に改善していきます。

さて、今日はここまでにしましょう。プロジェクトの内容やブログの内容も Github に載せる予定ですので、皆様からのご提案をお待ちしております。

コード: https://github.com/CraryPrimitiveMan/simple-framework/tree/0.7

ブログプロジェクト: https://github.com/CraryPrimitiveMan/create-your-own-php-framework

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

11ベストPHP URLショートナースクリプト(無料およびプレミアム) 11ベストPHP URLショートナースクリプト(無料およびプレミアム) Mar 03, 2025 am 10:49 AM

多くの場合、キーワードと追跡パラメーターで散らかった長いURLは、訪問者を阻止できます。 URL短縮スクリプトはソリューションを提供し、ソーシャルメディアやその他のプラットフォームに最適な簡潔なリンクを作成します。 これらのスクリプトは、個々のWebサイトにとって価値があります

Instagram APIの紹介 Instagram APIの紹介 Mar 02, 2025 am 09:32 AM

2012年のFacebookによる有名な買収に続いて、Instagramはサードパーティの使用のために2セットのAPIを採用しました。これらはInstagramグラフAPIとInstagram Basic Display APIです。

Laravelでフラッシュセッションデータを使用します Laravelでフラッシュセッションデータを使用します Mar 12, 2025 pm 05:08 PM

Laravelは、直感的なフラッシュメソッドを使用して、一時的なセッションデータの処理を簡素化します。これは、アプリケーション内に簡単なメッセージ、アラート、または通知を表示するのに最適です。 データは、デフォルトで次の要求のためにのみ持続します。 $リクエスト -

LaravelのバックエンドでReactアプリを構築する:パート2、React LaravelのバックエンドでReactアプリを構築する:パート2、React Mar 04, 2025 am 09:33 AM

これは、LaravelバックエンドとのReactアプリケーションの構築に関するシリーズの2番目と最終部分です。シリーズの最初の部分では、基本的な製品上場アプリケーションのためにLaravelを使用してRESTFUL APIを作成しました。このチュートリアルでは、開発者になります

Laravelテストでの簡略化されたHTTP応答のモッキング Laravelテストでの簡略化されたHTTP応答のモッキング Mar 12, 2025 pm 05:09 PM

Laravelは簡潔なHTTP応答シミュレーション構文を提供し、HTTP相互作用テストを簡素化します。このアプローチは、テストシミュレーションをより直感的にしながら、コード冗長性を大幅に削減します。 基本的な実装は、さまざまな応答タイプのショートカットを提供します。 Illuminate \ support \ facades \ httpを使用します。 http :: fake([[ 'google.com' => 'hello world'、 'github.com' => ['foo' => 'bar']、 'forge.laravel.com' =>

PHPのカール:REST APIでPHPカール拡張機能を使用する方法 PHPのカール:REST APIでPHPカール拡張機能を使用する方法 Mar 14, 2025 am 11:42 AM

PHPクライアントURL(CURL)拡張機能は、開発者にとって強力なツールであり、リモートサーバーやREST APIとのシームレスな対話を可能にします。尊敬されるマルチプロトコルファイル転送ライブラリであるLibcurlを活用することにより、PHP Curlは効率的なexecuを促進します

Codecanyonで12の最高のPHPチャットスクリプト Codecanyonで12の最高のPHPチャットスクリプト Mar 13, 2025 pm 12:08 PM

顧客の最も差し迫った問題にリアルタイムでインスタントソリューションを提供したいですか? ライブチャットを使用すると、顧客とのリアルタイムな会話を行い、すぐに問題を解決できます。それはあなたがあなたのカスタムにより速いサービスを提供することを可能にします

2025 PHP状況調査の発表 2025 PHP状況調査の発表 Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Surveyは、現在のPHP開発動向を調査しています。 開発者や企業に洞察を提供することを目的とした、フレームワークの使用、展開方法、および課題を調査します。 この調査では、現代のPHP Versioの成長が予想されています

See all articles