찾다
백엔드 개발PHP 튜토리얼构建自己的PHP框架实现Model类(3)

在之前的博客中,我们实现并完善了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으로 문의하세요.
PHP의 목적 : 동적 웹 사이트 구축PHP의 목적 : 동적 웹 사이트 구축Apr 15, 2025 am 12:18 AM

PHP는 동적 웹 사이트를 구축하는 데 사용되며 해당 핵심 기능에는 다음이 포함됩니다. 1. 데이터베이스와 연결하여 동적 컨텐츠를 생성하고 웹 페이지를 실시간으로 생성합니다. 2. 사용자 상호 작용 및 양식 제출을 처리하고 입력을 확인하고 작업에 응답합니다. 3. 개인화 된 경험을 제공하기 위해 세션 및 사용자 인증을 관리합니다. 4. 성능을 최적화하고 모범 사례를 따라 웹 사이트 효율성 및 보안을 개선하십시오.

PHP : 데이터베이스 및 서버 측 로직 처리PHP : 데이터베이스 및 서버 측 로직 처리Apr 15, 2025 am 12:15 AM

PHP는 MySQLI 및 PDO 확장 기능을 사용하여 데이터베이스 작업 및 서버 측 로직 프로세싱에서 상호 작용하고 세션 관리와 같은 기능을 통해 서버 측로 로직을 처리합니다. 1) MySQLI 또는 PDO를 사용하여 데이터베이스에 연결하고 SQL 쿼리를 실행하십시오. 2) 세션 관리 및 기타 기능을 통해 HTTP 요청 및 사용자 상태를 처리합니다. 3) 트랜잭션을 사용하여 데이터베이스 작업의 원자력을 보장하십시오. 4) SQL 주입 방지, 디버깅을 위해 예외 처리 및 폐쇄 연결을 사용하십시오. 5) 인덱싱 및 캐시를 통해 성능을 최적화하고, 읽을 수있는 코드를 작성하고, 오류 처리를 수행하십시오.

PHP에서 SQL 주입을 어떻게 방지합니까? (준비된 진술, pdo)PHP에서 SQL 주입을 어떻게 방지합니까? (준비된 진술, pdo)Apr 15, 2025 am 12:15 AM

PHP에서 전처리 문과 PDO를 사용하면 SQL 주입 공격을 효과적으로 방지 할 수 있습니다. 1) PDO를 사용하여 데이터베이스에 연결하고 오류 모드를 설정하십시오. 2) 준비 방법을 통해 전처리 명세서를 작성하고 자리 표시자를 사용하여 데이터를 전달하고 방법을 실행하십시오. 3) 쿼리 결과를 처리하고 코드의 보안 및 성능을 보장합니다.

PHP 및 Python : 코드 예제 및 비교PHP 및 Python : 코드 예제 및 비교Apr 15, 2025 am 12:07 AM

PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

PHP 실행 : 실제 예제 및 응용 프로그램PHP 실행 : 실제 예제 및 응용 프로그램Apr 14, 2025 am 12:19 AM

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다Apr 14, 2025 am 12:15 AM

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다Apr 14, 2025 am 12:13 AM

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP의 지속적인 관련성 : 여전히 살아 있습니까?PHP의 지속적인 관련성 : 여전히 살아 있습니까?Apr 14, 2025 am 12:12 AM

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

See all articles

핫 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를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구