1. Go to this page and download the library: Download webfiori/database library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
webfiori / database example snippets
use WebFiori\Database\ConnectionInfo;
use WebFiori\Database\Database;
$connection = new ConnectionInfo('mysql', 'root', '123456', 'testing_db');
$database = new Database($connection);
// Single class
$database->addTableFromClass(Users::class);
// Multiple classes at once
$database->addTablesFromClasses([Users::class, Posts::class, Comments::class]);
class Product {
public ?int $id = null;
public string $name;
public float $price;
}
use WebFiori\Database\Repository\AbstractRepository;
class ProductRepository extends AbstractRepository {
protected function getTableName(): string {
return 'products';
}
protected function getIdField(): string {
return 'id';
}
protected function toEntity(array $row): object {
$product = new Product();
$product->id = (int) $row['id'];
$product->name = $row['name'];
$product->price = (float) $row['price'];
return $product;
}
protected function toArray(object $entity): array {
return [
'id' => $entity->id,
'name' => $entity->name,
'price' => $entity->price
];
}
}
use WebFiori\Database\Schema\AbstractMigration;
class CreateUsersTable extends AbstractMigration {
public function up(Database $db): void {
$db->createBlueprint('users')->addColumns([
'id' => [ColOption::TYPE => DataType::INT, ColOption::PRIMARY => true, ColOption::AUTO_INCREMENT => true],
'name' => [ColOption::TYPE => DataType::VARCHAR, ColOption::SIZE => 100]
]);
$db->table('users')->createTable()->execute();
}
public function down(Database $db): void {
$db->raw("DROP TABLE users")->execute();
}
}
use WebFiori\Database\Schema\SchemaRunner;
$runner = new SchemaRunner($connectionInfo);
$runner->discoverFromPath(__DIR__ . '/migrations', 'App\\Migrations');
$runner->createSchemaTable();
$runner->apply();
class CreateReportsTable extends AbstractMigration {
public function getTargetConnections(): array {
return ['reporting-db']; // Only runs against the 'reporting-db' connection
}
public function up(Database $db): void {
// ...
}
public function down(Database $db): void {
// ...
}
}
use WebFiori\Database\Schema\AbstractSeeder;
class UsersSeeder extends AbstractSeeder {
public function run(Database $db): void {
$db->table('users')->insert([
'name' => 'Administrator',
'email' => '[email protected]'
])->execute();
}
}