webx/db

1.1.8 2016-08-24 10:44 UTC

This package is not auto-updated.

Last update: 2024-09-26 00:39:56 UTC


README

webx-db的主要功能和设计目标

  • 基于名称的自动转义参数化。
  • 支持嵌套事务(savepoint Xrollback to savepoint X)。
  • 带有违规键名称的键违规异常。
  • 在基于IOC的设计中易于使用。
  • 轻量级。

安装

* Packagist: webx-db

入门

    use WebX\Db\Db;
    use WebX\Db\Impl\DbImpl;

    $db = new DbImpl([
        "user" => "mysqlUser",
        "password" => "mysqlPassword",
        "database" => "mysqlDatabase"
    ]);

    //or

    $db = new DbImpl($mysqli); //Instance of mysqli

简单的插入操作

    $person = ["first"=>"Alex", "last"=>"Morris","email"=>"am@domain.com"];
    $db->execute("INSERT INTO people (first,last,email,phone) VALUES(:first,:last,:email,:phone)", $person);
    //SQL: INSERT INTO people (first,last,email,phone) VALUES('Alex','Morris','am@domain',NULL);

    $id = $db->insertId();          //The value of the autogenerated primary key.

简单的选择操作

    foreach($db->allRows("SELECT * FROM table") as $row) {
        echo($row->string('first'));
        echo($row->string('last'));
    }

带有键违规的插入

    $person = [...];
    try {
        $db->execute("INSERT INTO people (first,last,email) VALUES(:first,:last,:email)", $person);
        echo("Person registered");
    } catch(DbKeyException $e) {
        if($e->key()==='emailKey') { // Name of the defined unique key in MySQL
            echo("The {$person->string('email')} is already registered";
        } else {
            echo("Some other key violation occured.");
        }
    }

嵌套事务

    $db->startTx();
    $db->execute("INSERT INTO table (col) VALUES('1')");

        $db->startTx();
        $db->execute("INSERT INTO table (col) VALUES('2')"); // Will not be commited
        $db->rollbackTx();

        $db->startTx();
        $db->execute("INSERT INTO table (col) VALUES('3')");
        $db->commitTx();

    $db->commitTx();

注意:如果外部事务回滚,所有其内部事务也将回滚。

在闭包中包裹事务

如果闭包抛出异常,则执行将包裹在 startTx() commitTx()|rollbackTx() 中。

    $db->executeInTx(function($db) { // The db instance must be passed as the only argument to closure.
        $db->execute("INSERT INTO table (col) VALUES('1')");
        $db->execute("INSERT INTO table (col) VALUES('2')");

        if(true) { //Now the transaction will be rolled back
            throw new \Exception("An error occured");
        }
    });

如何运行测试

在项目根目录下

composer install

phpunit -c tests