dealnews / db
Database Library providing a PDO factory and CRUD operations
Requires
- php: ^8.0
- dealnews/data-mapper: ^3.1.1
- dealnews/get-config: ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.38
- php-parallel-lint/php-parallel-lint: ^1.3
- phpunit/phpunit: ^9.6
README
Factory
The factory creates PDO objects using \DealNews\GetConfigto read database settings and create a PDO database connection.
Supported Settings
Usage
Example:
$mydb = \DealNews\DB\Factory::init("mydb");
CRUD
The CRUD
class is a helper that wraps up common PDO logic for CRUD operations.
Basic Usage
$mydb = \DealNews\DB\Factory::init("mydb");
$crud = new \DealNews\DB\CRUD($mydb);
// Create
$result = $crud->create(
// table name
"test",
// data to add
[
"name" => $name,
"description" => $description,
]
);
// Read
$rows = $crud->read(
// table name
"test",
// where clause data
["id" => $id]
);
// Update
$result = $crud->update(
// table name
"test",
// data to update
["name" => "Test"],
// where clause data
["id" => $id]
);
// Delete
$result = $crud->delete(
// table name
"test",
// where clause data
["id" => $row["id"]]
);
Advanced Usage
The class also exposes a run
method which is used internally by the other
methods. Complex queries can be run using this method by providing an SQL
query and a parameter array which will be mapped to the prepared query. It
returns a PDOStatement object.
// Run a select with no parameters
$stmt = $crud->run("select * from table limit 10");
// Run a select query with paramters
$stmt = $crud->run(
"select * from table where foo = :foo"
[
":foo" => $foo
]
);
Testing
By default, only unit tests are run. To run the functional tests the host
machine will need to be a docker host. Also, the pdo_pgsql, pdo_mysql, and
pdo_sqlite extensions must be installed on the host machine. PHPUnit will
start and stop docker containers to test the MySQL and Postgres connections.
Use --group functional
when running PHPUnit to run these tests.