tasoft/php-pdo

v0.8.12 2023-02-08 17:12 UTC

This package is auto-updated.

Last update: 2024-09-08 20:57:27 UTC


README

此库通过添加一些有用的功能扩展了内置的 PDO 对象。

它添加了 Php 生成器以获取行并插入或更新记录。

简单的 SELECT

$gen = $PDO->select("SELECT * FROM XXX");
// Now $gen is a generator, that means nothing happens until you want to fetch the records.

// ... more code

// Now, fetch the SQL records:
foreach($gen as $record) {
    // ... 
}

也允许的是

$gen = $PDO->select("SELECT * FROM XXX WHERE id = ?", [$objectID]);
// For secure SQL request.

注入记录

$gen = $PDO->inject("INSERT INTO XXX (name, email) VALUES (?, ?)");
// Now again nothing happend yet.

// To insert records, just use.

$gen->send(["Thomas", "email@example.org"]);
// As many times you want!

请注意,SQL 语法是直接传递给内置的 Php PDO 对象。请参阅该文档以获取有关 SQL 脚本语言的更多信息。

映射

此库还允许将数据库的原始格式值映射到对象,反之亦然。

$PDO->setTypeMapper( new DateMapper() );
// Now the methods selectWithObjects and injectWithObjects will convert raw values into their object values.

$record = $PDO->selectOneWithObjects("SELECT * FROM XXX");
print_r($record);
/*
Might look like:
Array (
    'the_date' => TASoft\Util\ValueObject\Date ... ,
    'the_date_time' => TASoft\Util\ValueObject\DateTime ... ,
    'the_time' => TASoft\Util\ValueObject\Time ...
)

// SQL:
CREATE TABLE XXX (
    the_date DATE DEFAULT NULL,
    the_date_time DATETIME DEFAULT NULL,
    the_time TIME DEFAULT NULL
)
*/

// This also works backward:
$newDate = new TASoft\Util\ValueObject\Date("1999-05-23");
$PDO->injectWithObjcts("UPDATE XXX SET the_date = ? WHERE ...")->send([$newDate, ...]);

// Using MapperChain allows to combine more than one type mapper.

另一个优点是能够执行事务。
事务组合多个 SQL 语句,并确保每个都成功执行。
就像:全有或全无

$PDO->transaction(function() {
    /** @var TASoft\Util\PDO $this */
    $this->inject(....);
    
    $this->exec( .... );
    ...
});

如果在代码的任何地方发生异常,事务将被取消(回滚)。