構建自己的PHP框架--實現Model類(3)

来源:http://www.cnblogs.com/CraryPrimitiveMan/archive/2016/03/02/5235760.html
-Advertisement-
Play Games

完成Model中的findAll/updateAll/deleteAll/insert/update和delete方法~~


在之前的博客中,我們實現並完善了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方法很相似,明顯可以將公共的部分抽出來,然後我們就多瞭如下兩個方法:

    /**
     * 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部分的方法和將查找到的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;
    }

剩下的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;
    }

這樣基本的Model就算是暫時完成了,雖然可能還有很多問題和局限,但暫時先這樣了,我們之後有機會會一步一步的去完善。

好了,今天就先到這裡。項目內容和博客內容也都會放到Github上,歡迎大家提建議。

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

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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Web How to do distributed locking Writing Next Generation Reusable JavaScript Modules in ECMAScript 6 Essential Tools for Building SPAs with AngularJS...
  • dataGrid 其實就是一個HTML TABLE 想清楚這個以後,要設置多維表頭就好辦了 HTML代碼 <asp:DataGrid ID="DataGrid1" runat="server" onitemdatabound="DataGrid1_ItemDataBound"> </asp:Data
  • 1、為服務創建安裝程式 1)、返回到 Service1 的“設計”視圖。 2)、單擊設計器的背景以選擇服務本身,而不是它的任何內容。 3)、在“屬性”視窗中,單擊屬性列表下麵灰色區域中的“添加安裝程式”鏈接。 預設情況下,向您的項目添加包含兩個安裝程式的組件類。將該組件命名為ProjectInsta
  • 先來點與標題不相關的: CLR支持兩種程式集:弱命名程式集和強命名程式集。 兩者的區別在於強命名程式集使用發佈者的公鑰和私鑰進行簽名。由於程式集被唯一性地標識,所以當應用程式綁定到強命名程式集時,CLR可以應用一些已知安全的策略。 程式集可以採用兩種方式部署:私有或者全局。弱命名程式集只能以私有方式
  • 錯誤狀況: 下麵內容來自網路,自己也另有補充 原因:在安裝Framework v4.0之後,再啟用IIS,導致Framework沒有完全安裝 解決辦法:開始->所有程式->附件->滑鼠右鍵點擊“命令提示符”->以管理員身份運行-> 32位的win7:%windir%\Microsoft.NET\Fr
  • ------------------------------------------------ 重點提示: 1、程式的註釋:單行註釋、多行註釋; ------------------------------------------------ 第1節 .Net學習路線及幾個容易混淆的概念 C#過程
  • 在我們的程式中,經常會有一些耗時較長的運算,為了保證用戶體驗,不引起界面不響應,我們一般會採用多線程操作,讓耗時操作在後臺完成,完成後再進行處理或給出提示,在運行中,也會時時去刷新界面上的進度條等顯示,必要時還要控制後臺線程中斷當前操作。 以前,類似的應用會比較麻煩,需要寫的代碼較多,也很容易出現異
  • 函數功能:該函數將指定的消息發送到一個或多個視窗。此函數為指定的視窗調用視窗程式,直到視窗程式處理完消息再返回。該函數是應用程式和應用程式之間進行消息傳遞的主要手段之一。 函數原型:LRESULT SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...