ayela-emmanuel/ayela-orm

此包是一个最小化ORM设置,用于使用PDO与SQL数据库交互,但将数据库抽象为更面向对象的方案

v1.0.0 2024-09-17 21:14 UTC

This package is auto-updated.

Last update: 2024-09-30 17:20:35 UTC


README

AyelaORM是一个轻量级的PHP对象关系映射(ORM)包,旨在通过使用PHP的PDO扩展简化数据库交互。它提供了一个易于使用的接口来管理数据库模式和对象,动态处理表创建和更新,并支持模型之间的关系,从而减少了手动模式管理和复杂SQL查询的需要。

目录

  1. 安装
  2. 使用方法
  3. 高级查询
  4. 模式管理
  5. 数据类型和序列化
  6. 错误处理
  7. 许可证

安装

使用Composer安装包

composer require ayela-emmanuel/ayela-orm

确保为PHP安装启用了PDO扩展(默认为MySQL)。将必要的命名空间AyelaORM添加到您的项目中。

使用方法

数据库设置

在开始使用AyelaORM之前,您必须设置数据库连接

use AyelaORM\Database;

Database::setup('localhost', 'database_name', 'username', 'password', false);
  • host:数据库服务器主机(例如,localhost)。
  • db:数据库名称。
  • username:数据库用户名。
  • password:数据库密码。
  • frozen:如果true,则不会自动检查或更新数据库模式。

创建模型

要创建一个与数据库交互的模型,扩展DatabaseObject

namespace Models;

use AyelaORM\DatabaseObject;
use AyelaORM\SQLType;
use AyelaORM\SQLIgnore;

class User extends DatabaseObject
{
    public string $db_username;
    public string $db_email;
    public int $db_age;
    public \DateTime $db_created_at;

    #[SQLIgnore]
    public string $password; // Will not be stored in the database

    public function __construct()
    {
        parent::__construct();
        $this->db_created_at = new \DateTime();
    }
}

注意

  • 属性命名:打算用于数据库存储的属性应以前缀db_开头。在映射到数据库列时,将删除该前缀。
  • 类型处理:类从PHP属性类型推断SQL数据类型。
  • 属性:
    • 使用#[SQLType("...")]指定属性的自定义SQL类型。
    • 使用#[SQLIgnore]将属性排除在数据库模式之外。

在启动时注册您的模型,以确保模式是最新的

Models\User::register();

保存数据

要保存新对象到数据库

$user = new Models\User();
$user->db_username = 'john_doe';
$user->db_email = 'john@example.com';
$user->db_age = 30;
$user->password = 'securepassword'; // Will not be saved to the database
$user->save();

保存后,db_id属性将填充数据库中的主键值。

检索数据

您可以使用几个内置方法检索记录。

获取所有记录

$users = Models\User::list(1, 10); // Retrieve the first 10 users (page 1).

通过ID获取记录

$user = Models\User::getById(1);

获取第一条记录

$user = Models\User::first();

更新数据

通过ID更新记录的字段

Models\User::update(1, 'email', 'newemail@example.com');

删除数据

删除单个记录

Models\User::delete(1);

删除多条记录

$ids = [2, 3, 4];
Models\User::deleteGroup($ids);

高级查询

AyelaORM提供了高级查询功能,无需编写原始SQL。findWherefirstWhere方法允许您根据条件检索记录。

简单条件

提供一个关联数组,其中键是字段名称,值是要匹配的值。

$users = Models\User::findWhere(['username' => 'john_doe']);

检索第一个匹配的记录

$user = Models\User::firstWhere(['email' => 'john@example.com']);

高级条件

提供一个条件数组数组,每个数组都包含一个字段、运算符和值。

$users = Models\User::findWhere([
    ['age', '>', 25],
    ['status', '=', 'active']
]);

支持的运算符:=><>=<=!=<>LIKE

关系(连接)

AyelaORM使用外键支持模型之间的关系。

定义关系

class Author extends DatabaseObject
{
    public string $db_name;
    public string $db_email;
}

class Book extends DatabaseObject
{
    public string $db_title;
    public Author $db_author; // Relationship to Author
}

保存带关系的数据

$author = new Models\Author();
$author->db_name = 'Jane Doe';
$author->db_email = 'jane@example.com';
$author->save();

$book = new Models\Book();
$book->db_title = 'Learning AyelaORM';
$book->db_author = $author; // Set the Author object
$book->save();

检索带关系的数据

$book = Models\Book::getById(1);
echo $book->db_title; // Outputs: Learning AyelaORM
echo $book->db_author->db_name; // Outputs: Jane Doe

一对一和一对多关系

一对一示例

Author类中添加一个方法来检索相关的Book对象

class Author extends DatabaseObject
{
    // ...

    public function getBooks(): array
    {
        return Models\Book::findWhere([['author', '=', $this->db_id]]);
    }
}

// Usage
$author = Models\Author::getById(1);
$books = $author->getBooks();

多对多示例

创建联合表模型

class Student extends DatabaseObject
{
    public string $db_name;

    public function enrollInCourse(Course $course)
    {
        $enrollment = new StudentCourse();
        $enrollment->db_student = $this;
        $enrollment->db_course = $course;
        $enrollment->save();
    }

    public function getCourses(): array
    {
        $enrollments = StudentCourse::findWhere([['student', '=', $this->db_id]]);
        return array_map(fn($enrollment) => $enrollment->db_course, $enrollments);
    }
}

class Course extends DatabaseObject
{
    public string $db_title;

    public function getStudents(): array
    {
        $enrollments = StudentCourse::findWhere([['course', '=', $this->db_id]]);
        return array_map(fn($enrollment) => $enrollment->db_student, $enrollments);
    }
}

class StudentCourse extends DatabaseObject
{
    public Student $db_student;
    public Course $db_course;
}

模式管理

AyelaORM自动管理数据库模式更改。每次您在模型中定义或修改属性时,AyelaORM都会检查并相应地更新表结构。

自动模式更新

如果在数据库设置期间将frozen设置为false,则会在每次模型实例化时检查和更新模式。如果表不存在,则会创建表;如果检测到更改,则会添加或修改列。

Database::setup('localhost', 'database_name', 'username', 'password', false);

自定义SQL类型

您可以使用#[SQLType("...")]属性为模型属性指定自定义SQL类型。

class Article extends DatabaseObject
{
    #[SQLType("TEXT")]
    public string $db_content;

    #[SQLType("VARCHAR(100) UNIQUE")]
    public string $db_slug;
}

忽略属性

要排除属性从数据库模式,请使用#[SQLIgnore]属性。

class User extends DatabaseObject
{
    #[SQLIgnore]
    public string $password; // Will not be stored in the database
}

数据类型和序列化

AyelaORM处理各种数据类型,包括

  • 标量类型intfloatstringbool
  • DateTime:自动转换为数据库日期时间格式和从数据库日期时间格式转换
  • 数据库对象子类:存储为外键(关系)
  • 数组和可序列化对象:在存储之前序列化为JSON,在检索时反序列化

可序列化对象示例

class UserProfile
{
    public string $bio;
    public array $interests;
}

class User extends DatabaseObject
{
    public string $db_username;
    public UserProfile $db_profile; // Serializable object
}

// Saving
$profile = new UserProfile();
$profile->bio = 'Developer';
$profile->interests = ['coding', 'music'];

$user = new User();
$user->db_username = 'johndoe';
$user->db_profile = $profile;
$user->save();

// Retrieving
$user = User::getById(1);
echo $user->db_profile->bio; // Outputs: Developer

错误处理

如果在数据库操作期间发生错误,它将存储在对象的$last_error属性中。

$user = new Models\User();
$user->db_username = 'john_doe';

// Intentionally cause an error (e.g., missing required field)
if (!$user->save()) {
    echo "Error: " . $user->last_error->getMessage();
}

如果您遇到任何问题或有改进建议,请随时联系或提交问题!

注意:本文档涵盖了最新功能,并提供示例以帮助您开始使用AyelaORM。该软件包旨在简化您的数据库交互并有效地管理关系,让您能够专注于构建应用程序。