riverside/php-orm

PHP ORM 微型库和查询构建器

2.0.0 2024-09-14 17:01 UTC

This package is auto-updated.

Last update: 2024-09-14 17:08:30 UTC


README

PHP 微型 ORM 和查询构建器。

要求

  • PHP >= 7.1
  • PHP 扩展
    • PDO (ext-pdo)

安装

如果您的系统上尚未安装 Composer,您可以使用以下命令行安装它

$ curl -sS https://getcomposer.org/installer | php

接下来,将以下 require 条目添加到您项目根目录中的 composer.json 文件中。

{
    "require" : {
        "riverside/php-orm" : "^2.0"
    }
}

最后,使用 Composer 安装 php-orm 及其依赖项

$ php composer.phar install 

配置

在您的项目中包含自动加载

require __DIR__ . '/vendor/autoload.php';

通过设置以下环境变量配置数据库凭据: USERNAMEPASSWORDDATABASEHOSTPORTDRIVERCHARSETCOLLATION。它们必须以您的模型中的 $connection 属性值作为前缀,全部大写并使用下划线。默认的 $connection 属性值是 'default'。例如

<?php
putenv("DEFAULT_USERNAME=your_username");
putenv("DEFAULT_PASSWORD=your_password");
putenv("DEFAULT_DATABASE=your_database");
putenv("DEFAULT_HOST=localhost");
putenv("DEFAULT_PORT=3306");
putenv("DEFAULT_DRIVER=mysql");
putenv("DEFAULT_CHARSET=utf8mb4");
putenv("DEFAULT_COLLATION=utf8mb4_general_ci");

驱动程序

以下驱动程序受支持: mysqlocifirebirdpgsqlsqlitesybasemssqldblibcubrid4D

数据库

表: users

模型

定义您自己的模型

<?php
use Riverside\Orm\DB;

class User extends DB
{
    protected $table = 'users';
    
    protected $attributes = ['id', 'name', 'email'];
    
    // protected $connection = 'backup';
    
    public static function factory()
    {
        return new self();
    }
}

查询构建器

  • 使用模型:使用 factory 方法创建一个模型的实例。然后链式调用多个方法。以下是一个简单的 CRUD 示例
$id = User::factory()->insert(['name' => 'Chris', 'email' => 'chris@aol.com']);
$user = User::factory()->where('id', $id)->get();
$affected_rows = User::factory()->where('id', $id)->update(['name' => 'Chris Johnson']);
$affected_rows = User::factory()->where('id', $id)->delete();
  • 不使用模型:创建 Riverside\Orm\DB 类的新实例
$db = new \Riverside\Orm\DB();
$db->table('users')->get();

API