search
HomeDatabaseMysql TutorialHow to write your own database package (4)

How to write your own database package (4)

Apr 04, 2017 pm 02:26 PM
Database encapsulation


Test database source

In fact, it should have been handed over in the first issue, but it doesn’t hurt to mention it now
ReferenceInstallationmysqlSample database sakila

Scenario description

I have a database (sakila) for testing, with a table (actor) in it, now we will combine it with Model Class binding can easily read data


First, create a new class. The class name is arbitrary, but it is recommended to be consistent with the table name

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;];

}

Have you found it? Isn’t it very concise? Apart from all the comments you can even set it up with just one line


For example

  • No conditions required, I just want to read all the data in the table

<?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);

Return results

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)

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

More readable High and applicable to the current requirements of writing

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

or

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

Return results

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)

......
  • I want search first_name contains Data for the letter L, but do not need the first 5 pieces of data. Take the next 10 pieces of data. If you want to view the first_name and last_name fields, it is enough.
    The most readable way of writing,
    will give you a preview, PaginationThe prototype of (paginate) is here

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

    Return results

    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)

    Want more examples? Leave a message and I will give the function chain in the comment area


DebuggingTips

Sometimes the lack of understanding of SQL statements may lead to BUG. At this time, you want to look at the native For SQL statements, you can add

// 读取数据
    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);
    }

to the read() function in Connector.php. Taking the last example as an example, the following two lines will be output:

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)


The above is the detailed content of How to write your own database package (4). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software