alphasoft-fr/data-model

PHP 数据建模

2.0.1 2024-03-19 13:57 UTC

This package is auto-updated.

Last update: 2024-09-19 14:57:10 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

安装

使用 Composer

Composer 需求

composer require alphasoft-fr/data-model

需求

  • PHP 版本 7.3

使用

创建模型

要创建新的模型,扩展 Model 类并实现所需的抽象方法: getDefaultAttributesgetDefaultColumnMapping

use AlphaSoft\DataModel\Model;

class UserModel extends Model
{
    protected static function getDefaultAttributes(): array
    {
        return [
            'fullName' => null,
            'age' => null,
            'isActive' => true,
        ];
    }

    protected static function getDefaultColumnMapping(): array
    {
        return [
            'fullName' => 'full_name',
            'age' => 'user_age',
        ];
    }
    
    public static function getPrimaryKeyColumn(): string
    {
        return 'id'; // Replace 'id' with the actual primary key column name
    }
}

数据填充

您可以使用构造函数或 hydrate 方法创建新的模型实例并将其与数据填充。

$data = [
    'full_name' => 'John Doe',
    'user_age' => 30,
    // ...
];

$user = new UserModel($data);

// Alternatively
$user = new UserModel();
$user->hydrate($data);

获取和设置属性

您可以使用getter和setter方法访问属性。属性会根据列映射配置自动映射到相应的列。

$fullName = $user->getString('fullName');
$age = $user->getInt('age');

$user->set('age', 31);
$user->set('isActive', false);

转换为数组

您可以使用 toArray 方法将模型转换为数组。

$userArray = $user->toArray();

与 PDO 一起使用

假设我们有一个基于 Model 类的 UserModel 类,我们想要在数据库中管理用户数据。

示例:插入数据

use YourNamespace\UserModel;
use PDO;

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=yourdb", "username", "password");

// Create a new UserModel instance
$user = new UserModel();
$user->set('fullName', 'Jane Smith');
$user->set('age', 25);

// Insert the new user data into the database
$columns = implode(', ', array_keys($user->toDb()));
$values = ':' . implode(', :', array_keys($user->toDb()));
$sql = "INSERT INTO users ($columns) VALUES ($values)";
$stmt = $pdo->prepare($sql);
foreach ($user->toDb() as $column => $value) {
    $stmt->bindValue(":$column", $value);
}
$stmt->execute();

$insertedPrimaryKeyValue = $pdo->lastInsertId();
echo "User inserted with primary key: $insertedPrimaryKeyValue\n";

示例:更新数据

use YourNamespace\UserModel;
use PDO;

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=yourdb", "username", "password");

// Retrieve user data from the database
$primaryKeyValue = 1; // Replace with the primary key value of the user you want to update
$sql = "SELECT * FROM users WHERE " . UserModel::getPrimaryKeyColumn() . " = :primaryKeyValue";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':primaryKeyValue', $primaryKeyValue);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);

// Create an instance of UserModel
$user = new UserModel($data);

// Modify object attributes
$user->set('fullName', 'Jane Smith');
$user->set('age', 25);

// Update the changes in the database
$updates = [];
foreach ($user->toDb() as $column => $value) {
    $updates[] = "$column = :$column";
}
$sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE " . UserModel::getPrimaryKeyColumn() . " = :" .UserModel::getPrimaryKeyColumn();
$stmt = $pdo->prepare($sql);
foreach ($user->toDb() as $column => $value) {
    $stmt->bindValue(":$column", $value);
}
$stmt->execute();

echo "User updated with primary key: $primaryKeyValue\n";

希望这些示例能满足您的需求。如果您有任何进一步的问题或需要更多帮助,请随时提问!

可用方法

Model 类提供了以下方法来操作对象数据

  • hydrate(array $data): 使用提供的数据填充对象。
  • toArray(): 将对象转换为关联数组。
  • get(string $property): 获取对象属性的值。
  • set(string $property, $value): 设置对象属性的值。
  • toDb(): 将对象转换为数据库插入准备的关联数组。

类型特定的检索

您还可以使用专用方法通过特定数据类型检索属性值。这些方法提供类型检查,并且在属性未定义或值类型错误时不允许默认值。

  • getString 获取字符串值。
$lastname = $user->getString('lastname', 'Doe'); // Retrieves 'Doe' if 'lastname' exists and is a string
  • getInt 获取整数值。
$age = $user->getInt('age', 25); // Retrieves 25 if 'age' exists and is an integer
  • getFloat 获取浮点值。
$price = $product->getFloat('price', 0.0); // Retrieves 0.0 if 'price' exists and is a float
  • getBool 获取布尔值。
$isActive = $user->getBool('isActive', false); // Retrieves false if 'isActive' exists and is a boolean
  • getArray 获取数组。
$tags = $post->getArray('tags', []); // Retrieves an empty array if 'tags' exists and is an array
  • getInstanceOf 获取指定类的实例,如果存在且是指定类的实例,则返回 null。
$profile = $user->getInstanceOf('profile', Profile::class); // Retrieves an instance of Profile or null if 'profile' exists and is an instance of Profile
  • getDateTime 获取 DateTimeInterface 实例,可选地指定解析格式。
$createdAt = $post->getDateTime('created_at', 'Y-m-d H:i:s'); // Retrieves a DateTimeInterface instance or null if 'created_at' exists and is convertible to a valid date

请注意,如果属性未定义或值类型错误,这些方法将抛出异常。如果您想要允许默认值,可以使用带有默认值的先前示例,但它们在这些情况下不会抛出异常。

配置属性和列

要配置模型中的属性和列,您需要在您的模型类中实现以下抽象方法

  • getDefaultAttributes(): 定义对象的默认属性。

此方法应实现以返回表示对象默认属性的关联数组,包括它们的默认值。

例如

protected static function getDefaultAttributes(): array
{
    return [
        'id' => null,
        'fullName' => null,
        'age' => 0,
        'isActive' => true,
    ];
}
  • getDefaultColumnMapping(): 定义对象属性与数据库列之间的映射。

此方法应实现以返回将对象属性映射到其对应数据库列的关联数组。

例如

protected static function getDefaultColumnMapping(): array
{
    return [
        'fullName' => 'full_name',
        'age' => 'user_age',
        'isActive' => 'is_active',
    ];
}
  • getPrimaryKeyColumn(): 获取模型的键列名称。

例如

public static function getPrimaryKeyColumn(): string
{
    return 'id'; // Replace 'id' with the actual primary key column name
}

此方法应由子类实现,以返回对应数据库表的模型的主键列名称。

方法 getPrimaryKeyValue()

getPrimaryKeyValue() 方法是一个工具函数,允许您获取模型对象的 主键列值。此方法在您需要获取模型对象的主键值以执行数据库中的更新或删除操作时非常有用。

此方法直接利用 get() 方法根据配置的主键列名称检索主键列的值。

以下是一个说明在模型类上下文中使用 getPrimaryKeyValue() 方法的示例

use AlphaSoft\DataModel\Model;

class UserModel extends Model
{
    protected static function getDefaultAttributes(): array
    {
        return [
            'id' => null,
            'fullName' => null,
            'age' => null,
            'isActive' => true,
        ];
    }

    protected static function getDefaultColumnMapping(): array
    {
        return [
            'id' => 'user_id',
            'fullName' => 'full_name',
            'age' => 'user_age',
            'isActive' => 'is_active',
        ];
    }
    
    public static function getPrimaryKeyColumn(): string
    {
        return 'id'; // Replace 'id' with the actual primary key column name
    }
}

// ...

// Creating a UserModel instance
$userData = [
    'id' => 1,
    'fullName' => 'John Doe',
    'age' => 30,
    'isActive' => true,
];
$user = new UserModel($userData);

// Getting the primary key value
$primaryKeyValue = $user->getPrimaryKeyValue();
echo "Primary Key Value: $primaryKeyValue\n"; // Output: Primary Key Value: 1

在此示例中,getPrimaryKeyValue() 方法直接使用 get() 方法从模型对象(在这种情况下为用户的ID)中检索主键列的值。这是一种方便的方式,可以获取主键以进行后续操作,例如在数据库中更新或删除数据。

始终确保调整值和列名称以匹配您的特定模型和数据库配置。

ModelFactory

ModelFactory 类提供方便的方法,从数据数组创建您的模型类和集合的实例。这在您需要将原始数据转换为完整填充的模型实例的场景中特别有用。

使用

首先,在文件顶部包含 ModelFactory 类所需的命名空间

use AlphaSoft\DataModel\Factory\ModelFactory;

创建单个模型实例

您可以使用 ModelFactory 类的 createModel 方法使用数据数组创建您的模型的单个实例

$modelData = [
    'fullName' => 'John Doe',
    'age' => 30,
    // ... other properties
];

$model = ModelFactory::createModel(YourModelClass::class, $modelData);

YourModelClass 替换为您的模型的实际类名。

创建模型实例集合

如果您有一个表示多个模型的多个数据数组,您可以使用 createCollection 方法创建模型实例的集合

$collectionData = [
    // ... array of model data
];

$collection = ModelFactory::createCollection(YourModelClass::class, $collectionData);

YourModelClass 替换为您的实际模型类名。

示例

以下是一个演示如何使用 ModelFactory 类创建模型实例的示例

use AlphaSoft\DataModel\Factory\ModelFactory;
use YourNamespace\UserModel;

// Sample data for a single model instance
$modelData = [
    'fullName' => 'Jane Smith',
    'age' => 25,
    // ... other properties
];

// Create a single model instance
$model = ModelFactory::createModel(UserModel::class, $modelData);

// Sample data for a collection of model instances
$collectionData = [
    // ... array of model data
];

// Create a collection of model instances
$collection = ModelFactory::createCollection(UserModel::class, $collectionData);

// Use the $model and $collection objects as needed

请记住调整命名空间和类名以匹配您的实际项目结构。

注意

在开始使用 ModelFactory 类之前,请确保您的模型类已设置好,以便与它无缝工作。 ModelFactory 假设您的模型扩展了 Model 类,并且设计为从数据数组中填充。

许可证

此软件包是开源软件,根据 MIT 许可证 许可。