plasma/schemas

模式将任何数据源映射到PHP对象。

v0.4.0 2021-02-28 14:52 UTC

This package is auto-updated.

Last update: 2024-09-09 23:28:52 UTC


README

Schemas是Plasma的简单对象关系映射器(ORM)。Schemas将任何数据源映射到PHP对象。

入门指南

Schemas可以通过composer安装。

composer require plasma/schemas

首先,您需要创建一个Plasma客户端,然后使用创建的客户端创建一个Repository(充当客户端)。然后,您需要创建您的模式类及其目录。您需要将这些目录注册到Repository。

目录从查询结果构建模式并与仓库进行查询交互。

之后,对Repository的queryexecute方法的每次调用都将为您提供具有Schema实例的专用SchemaCollection。对Repository::prepare的调用将在成功的情况下提供一个包装的Statement实例。包装器具有与Repository相同的目的。

$loop = \React\EventLoop\Factory::create();
$factory = new \Plasma\Drivers\MySQL\DriverFactory($loop, array());

$client = \Plasma\Client::create($factory, 'root:1234@localhost');
$repository = new \Plasma\Schemas\Repository($client);

/**
 * Our example table "users" consists of two columns:
 * - id ; auto incremented integer (length 12) primary
 * - name ; varchar(255) utf8mb4_generl_ci
 */
class Users extends \Plasma\Schemas\AbstractSchema {
    public $id;
    public $name;
    
    /**
     * Returns the schema definition.
     * @return \Plasma\Schemas\ColumnDefinitionInterface[]
     */
    static function getDefinition(): array {
        return array(
            // A generic column definition builder
            // solely for ease of use and does not
            // have to be used.
            // Any Plasma Column Definition
            // can be used.
            
            static::getColDefBuilder()
                ->name('id')
                ->type('INTEGER')
                ->length(12)
                ->autoIncrement()
                ->primary()
                ->getDefinition(),
            static::getColDefBuilder()
                ->name('name')
                ->type('VARCHAR')
                ->length(255)
                ->getDefinition()
        );
    }
    
    /**
     * Returns the name of the table.
     * @return string
     */
    static function getTableName(): string {
        return 'users';
    }
    
    /**
     * Returns the name of the identifier column (primary or unique), or null.
     * @return string|null
     */
    static function getIdentifierColumn(): ?string {
        return 'id';
    }
}

// null is the SQL grammar (see plasma/sql-common)
$builderA = new \Plasma\Schemas\SQLDirectory(Users::class, null);
$repository->registerDirectory('users', $builderA);

$repository->execute('SELECT * FROM `users`', array())
    ->done(function (\Plasma\Schemas\SchemaCollection $collection) {
        // Do something with the collection
    });

$loop->run();

预加载

Schemas有一个名为预加载的机制。

预加载是在模式加载的同时加载外键引用的方式,并使您的模式始终填充外键引用模式。预加载的确切加载方式取决于目录实现。

预加载具有ALWAYS获取模式的远程目标,并自动处理。具有LAZY获取模式的远程目标不会自动加载,需要在模式上显式调用resolveForeignTargets

是否使用一种获取模式而不是另一种取决于用例。只预加载您实际上始终需要的模式是有意义的。

预加载通过ColumnDefinitionInterface支持。当前实现是ColumnDefinition实现和ColumnDefinitionBuilder

文档

https://plasmaphp.github.io/schemas/