hulotte/database

Hulotte 数据库管理组件

1.0.1 2021-01-06 16:20 UTC

This package is auto-updated.

Last update: 2024-09-06 23:57:45 UTC


README

描述

Hulotte Database 是一个对象关系映射库。

安装

使用 Hulotte Database 的最简单方法是使用 Composer,命令如下

$ composer require hulotte/database

描述

Hulotte Database 由两个类组成:Database 和 Repository。

Database 类用于与数据库建立连接,需要一个 PDO 实例。

Repository 类是所有用作表存储库的类的父类。它需要一个 Database 类的实例。

如何使用 Hulotte Database:简单方法

如描述中所示,我们需要实例化 PDO 并将其传递给 Database

$pdo = new \PDO(
    'mysql:host=<database_host>;dbname=<database_name>', 
    '<username>', 
    '<password>'
);

$database = new \Hulotte\Database\Database($pdo);

使用示例

// Launch a "fetchAll" query
$results = $database->query('SELECT * FROM user WHERE id = 1');

// Launch a "fetchAll" query with prepare
$results = $database->prepare('SELECT * FROM user WHERE id = :id', [':id' => 1]);

// You can use same methods to launch a simple fetch by passing "true" to the last argument
$results = $database->query('SELECT * FROM user WHERE id = 1', null, true);
$results = $database->prepare('SELECT * FROM user WHERE id = :id', [':id' => 1], null, true)

// The requests which are not in "select" return an instance of PDOStatement
$result = $database->query('UPDATE test SET name = "Fifi" WHERE id = 1)');

// PDO's lastInsertId method is also accessible
$result = $database->getLastInsertId();

如何使用 Hulotte Database:存储库方法

为了举例,让我们假设数据库中存在一个用户表。

首先,我们需要创建一个具有设置器和获取器的实体

class UserEntity
{
    private int $id;
    
    private string $name;
    
    public function getId(): int
    {
        return $this->id;
    }
    
    public function setId(int $id): void
    {
        $this->id = $id;
    }
    
    public function getName(): string
    {
        return $this->name;
    }
    
    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

现在我们可以为用户表创建一个存储库。这个存储库必须扩展 Hulotte\Database\Repository 类。存储库类需要一个 Database 类的实例。

class UserRepository extends \Hulotte\Database\Repository
{
    // Define the Entity class
    protected string $entity = UserEntity::class;
    
    // Define the table's name in database
    protected string $table = 'user';
}

$userRepository = new UserRepository($database);

使用示例

存储库类有几个动态方法

// Get on user by is id
$result = $userRepository->find(1); // Return a UserEntity

// Get all the users
$results = $userRepository->all(); // Return an array of UserEntity

// Get the last insert id
$result = $userRepository->getLastInsertId();

如果您需要发送特定的查询,可以使用 Repository query() 方法。行为与 Database 类相同,除了查询和 prepare 方法合并为单个方法。

// On the UserRepository class
public function findByName(string $name): userEntity
{
    $statement = 'SELECT * FROM ' . $this->table . ' WHERE name = :name';
    
    return $this->query(
        $statement, // Your query 
        [':name' => $name], // Send params call a prepared request
        true // Send true if you want only one result. Send nothing if you want many results
    );
}