백엔드 개발 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方法很相似,明显可以将公共的部分抽出来,然后我们就多了如下两个方法:

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

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 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 Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) 11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개 Instagram API 소개 Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축 Laravel Back End : Part 2, React가있는 React 앱 구축 Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 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