Home >Database >Mysql Tutorial >How to write your own database package (5)

How to write your own database package (5)

PHPz
PHPzOriginal
2017-04-04 14:27:431561browse


Basic idea

Before starting the code, we need to recall some of the problems we face daily, or bad experiences

When implementing business logic When, we often encounter the following similar scenarios

Confirm whether Mr. A (id=233) is a member, if so, modify the field 'status' to 'active', otherwiseDeleteIt

is usually written like this when there is no framework (the following code skips all pdo logic)

// 首先查询A先生的数据, 获取他的身份
$a = 'select * from users where id = 233';
// 判定是否为会员
if($a->member === true)
    // 是就修改字段
   $b = 'update users set status = 'active' where id = 233';
else
   // 否就删除数据
   $b= 'delete from users where id = 233';

Note , This is because we have simplified all the steps of pdo. Just think about more complex business logic. I have seen thousands of lines filled with SQL statements. The code readability is equal to 0, and reconstruction is incompetent.
So, based on Why do we need to write so much? It can be simplified!

Reoperable data

When the data is returned, it is converted into an instance, and the instance comes with Function, can perform certain operations

This is the reason why the data returned will be put into the function cast() for conversion in the query article

After using encapsulation You can do this

// 首先查询A先生的数据, 获取他的身份
$a = User::find(233);
// 判定是否存在该id和该id是否为会员
if($a & $a->member)
    // 是就修改字段
   $b = $a->update(['status'=>'active']);
else
   // 否就删除数据
   $b= $a->delete();

Next we need to think

How to modify the database data?

This is my own superficial answer

In common situations we need to use conditional syntax to specify the range of data that needs to be modified and filter the data that does not need to be rewritten

According to the above description, there are three examples

  1. Do not specify the range at all, Modify all data in the table

    update Actor set first_name = 'new data'
  2. Specify the range, modify multiple pieces of data that match the conditions

    update Actor set first_name = 'new data' where first_name like '%L%'
  3. Specify the range, modify the specified single piece of data based on the identity of the table key or unique key

    update Actor set first_name = 'new data' where actor_id = 10

According to the above three types , we can start developing the update function,
PS: I cannot understand/have never used the too advanced update statement because of my inexperience. Welcome to leave a message


Builder.php

Add the update function in the last line

// 改写数据库数据
    public function update(array $values) {
        // 如果写保护已经开启,跳出错误
        if($this->writeLock) throw new Exception("data is not allow to update");

        // 编译update语句
        $sql = $this->grammar->compileUpdate($this, $values);

        // 将所有变量的值合成一个数组, 其中包括条件语句部分
        $bindings = array_values(array_merge($values, $this->getBindings()));

        // 返回改写结果,成功true失败false
        return $this->connector->update($sql, $bindings);
    }

Grammar.php

Add the compileUpdate function in the last line

    public function compileUpdate(Builder $query, $values) {
        // 循环$values, 记得引用
        foreach ($values as $key => &$value) 
            // 将所有$value改成对应的$key=?
            $value = $key.' = ?';

        // 将$values中的之全部掏出在连接起来
        $columns = implode(', ', array_values($values));

        // 附上where语句如果有
        // 由于更复杂的sql update语句我还没试过, 为了不坑人, 所以限制只有where语法有效
        // 欢迎提供更复杂的where语句
        $where = is_null($query->wheres) ? '' : $this->compileWheres($query);

        // 返回update语句
        return trim("update $query->from set $columns $where");
    }

Model.php

Add function save, see the example below for usage

// 一种更快捷的update方式
    public function save() {
        return $this->update((array)$this->data);
    }

Example

  • Modify the specified data

$a = Actor::where('first_name', 'ANGELINA')
    ->update(['last_name'=>'changed']);
dd($a);
  • Operation data instance again

$a = Actor::where('first_name', 'ANGELINA')
    ->first();
dd($a->update(['last_name'=>'again']));
  • Operation data instance again, another usage

$a = Actor::where('first_name', 'ANGELINA')
    ->first();

$a->last_name = 'save';
dd($a->save());

Return results

boolean true
// 失败返回false


The above is the detailed content of How to write your own database package (5). 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