>  기사  >  데이터 베이스  >  자신만의 데이터베이스 패키지를 작성하는 방법 (4)

자신만의 데이터베이스 패키지를 작성하는 방법 (4)

PHPz
PHPz원래의
2017-04-04 14:26:421728검색


테스트 데이터베이스 소스

사실 창간때 넘겨줬어야 했는데 지금 언급해도 나쁠 건 없군요
참고설치mysql샘플 데이터베이스 sakila

시나리오 설명

테이블(배우)이 있는 테스트용 데이터베이스(sakila)가 있습니다. 이제 우리는 Model클래스와 바인딩하면 데이터 읽기가 쉬워집니다


먼저 새 클래스를 만듭니다. 클래스 이름은 임의적이지만 일관성을 유지하는 것이 좋습니다. 테이블 이름

Actor .php

<?php
/**
* 数据库中的Actor表
* 继承Model的属性和函数
*/
class Actor extends Model {
    // 由于我们的数据库表名和当前的类名是一样的,可以直接省略这一步
    // protected $table = &#39;Actor&#39;;

    // 设置Actor表的主键
    protected $identity = &#39;actor_id&#39;;

    // 或者设置unique key
    // 如果unique key只有一个
    // protected $unique = &#39;actor_id&#39;;
    // 如果多个unique key
    // protected $unique = [&#39;first_name&#39;, &#39;last_name&#39;];

}

알고 계셨나요? 매우 간결하지 않나요? 모든 댓글 외에도 간단히 설정할 수 있습니다. 한 줄


예를 들어

  • 그냥 아무 조건 없이 테이블의 모든 데이터를 읽고 싶어요

<?php
/**
 * 特别预告
 * 想必有人发现需要require的文件可能多了一些
 * 这可以用自动载入来解决
 * 敬请期待
 */
// 辅助函数我都写helper里了
require &#39;lib/helper.php&#39;;
require &#39;lib/Connector.php&#39;;
require &#39;lib/Builder.php&#39;;
require &#39;lib/Grammar.php&#39;;
require &#39;lib/Model.php&#39;;
require &#39;model/Actor.php&#39;;

$a = Actor::get();
dd($a);

결과 반환

array (size=197)
  0 => 
    object(Actor)[207]
      public 'actor_id' => string '1' (length=1)
      public 'first_name' => string 'PENELOPE' (length=8)
      public 'last_name' => string 'GUINESS' (length=7)
      public 'last_update' => string '2006-02-15 04:34:33' (length=19)
  1 => 
    object(Actor)[211]
      public 'actor_id' => string '2' (length=1)
      public 'first_name' => string 'NICK' (length=4)
      public 'last_name' => string 'WAHLBERG' (length=8)
      public 'last_update' => string '2006-02-15 04:34:33' (length=19)
  2 => 
    object(Actor)[215]
      public 'actor_id' => string '3' (length=1)
      public 'first_name' => string 'ED' (length=2)
      public 'last_name' => string 'CHASE' (length=5)
      public 'last_update' => string '2006-02-15 04:34:33' (length=19)
  3 => 
    object(Actor)[219]
      public 'actor_id' => string '4' (length=1)
      public 'first_name' => string 'JENNIFER' (length=8)
      public 'last_name' => string 'DAVIS' (length=5)
      public 'last_update' => string '2006-02-15 04:34:33' (length=19)

// 更多数据......

가독성이 높고 현재 요구 사항에 적합한 쓰기 방법은

// 这回多一个小要求, 我只想看以下两个声明的字段
$a = Actor::all(['first_name', 'last_name']);

또는

$a = Actor::select('first_name', 'last_name')->get();

가 결과를 반환합니다.

array (size=197)
  0 => 
    object(Actor)[207]
      public 'first_name' => string 'ADAM' (length=4)
      public 'last_name' => string 'GRANT' (length=5)
  1 => 
    object(Actor)[211]
      public 'first_name' => string 'ADAM' (length=4)
      public 'last_name' => string 'HOPPER' (length=6)
  2 => 
    object(Actor)[215]
      public 'first_name' => string 'AL' (length=2)
      public 'last_name' => string 'GARLAND' (length=7)
  3 => 
    object(Actor)[219]
      public 'first_name' => string 'ALAN' (length=4)
      public 'last_name' => string 'DREYFUSS' (length=8)

......
  • 문자 L에 포함된 first_name을 검색하고 싶지만 처음 5개의 데이터는 필요하지 않고 원하는 경우 다음 10개의 데이터를 가져옵니다. first_name 및 last_name 필드를 보려면 충분합니다.
    가장 읽기 쉬운 작성 방법인
    미리 살펴보겠습니다. 페이지 매김의 프로토타입(paginate)이 여기에 있습니다

    $a = Actor::select('first_name', 'last_name')
      ->where('first_name', 'like', '%L%')
      ->skip(5) // 略过5条
      ->take(10) // 拿取10条
      ->get();

    결과 반환

    array (size=10)
    0 => 
      object(Actor)[20]
        public 'first_name' => string 'ANGELA' (length=6)
        public 'last_name' => string 'HUDSON' (length=6)
    1 => 
      object(Actor)[24]
        public 'first_name' => string 'ANGELA' (length=6)
        public 'last_name' => string 'WITHERSPOON' (length=11)
    2 => 
      object(Actor)[28]
        public 'first_name' => string 'ANGELINA' (length=8)
        public 'last_name' => string 'ASTAIRE' (length=7)
    3 => 
      object(Actor)[32]
        public 'first_name' => string 'BELA' (length=4)
        public 'last_name' => string 'WALKEN' (length=6)
    4 => 
      object(Actor)[36]
        public 'first_name' => string 'CHARLIZE' (length=8)
        public 'last_name' => string 'DENCH' (length=5)
    5 => 
      object(Actor)[40]
        public 'first_name' => string 'DARYL' (length=5)
        public 'last_name' => string 'CRAWFORD' (length=8)
    6 => 
      object(Actor)[44]
        public 'first_name' => string 'DARYL' (length=5)
        public 'last_name' => string 'WAHLBERG' (length=8)
    7 => 
      object(Actor)[48]
        public 'first_name' => string 'ELLEN' (length=5)
        public 'last_name' => string 'PRESLEY' (length=7)
    8 => 
      object(Actor)[52]
        public 'first_name' => string 'ELVIS' (length=5)
        public 'last_name' => string 'MARX' (length=4)
    9 => 
      object(Actor)[56]
        public 'first_name' => string 'EMILY' (length=5)
        public 'last_name' => string 'DEE' (length=3)

    더 많은 예시를 원하시나요? 메시지를 남겨주시면 댓글 영역에 함수 체인을 제공하겠습니다.


디버깅

때때로 SQL 문에 대한 이해가 부족하여 BUG가 발생할 수 있습니다. 이때 네이티브 SQL 문에 대해서는 읽기에

// 读取数据
    public function read($sql, $bindings) {
        var_dump($sql); // 就是这一句
        var_dump($bindings); // 还可以确认条件值是否正确对应
        // 将sql语句放入预处理函数
        $statement = $this->connection->prepare($sql);
        // 将附带参数带入pdo实例
        $this->bindValues($statement, $bindings);
        // 执行
        $statement->execute();
        // 返回所有合法数据, 以Object对象为数据类型
        return $statement->fetchAll(PDO::FETCH_OBJ);
    }

를 추가하면 됩니다. () 함수를 예로 들면, 다음 두 줄이 출력됩니다:

string 'select first_name, last_name from Actor where Actor.first_name like ? order by 1 asc limit 10 offset 5' (length=102)

array (size=1)
  0 => string '%L%' (length=3)


위 내용은 자신만의 데이터베이스 패키지를 작성하는 방법 (4)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.