genesis/persistence

此包最新版本(2.0.0)没有可用的许可信息。

2.0.0 2018-02-06 23:00 UTC

This package is not auto-updated.

Last update: 2024-09-22 11:10:14 UTC


README

介绍

此包允许实现超级快速的模式,可以直接将数据库模型导入到数据库管理器。

用法

要使用mapperService,请创建一个模型(您可以根据需要命名),该模型扩展了BaseModel。您的模型不需要实现任何getter和setter,这些将由BaseModel提供。您必须将所有模型属性声明为protected。

创建模型

namespace myApp;

use Genesis\Services\Persistence\Model\BaseModel;

class MyItemModel extends BaseModel
{
    protected $name = 'text not null unique';

    protected $description = 'text default null';

    protected $userId = 'integer not null';

    /**
     * Enforced by the constructor.
     *
     * @return array
     */
    protected function getRequiredFields()
    {
        return [
            'userId'
        ];
    }
}

在上面的示例中,您的模型定义了数据库的设置和通信方式。每个属性将定义其类型和约束。请注意,id属性由BaseModel继承,并将包含在所有表中作为必填项。

使用mapper的模型

mapper提供了一层简单而强大的抽象。它理解您的模型如何从数据库中保存和检索。

实例化

use Genesis\Services\Persistence;

// Configuration for the databaseService.
$dbParams = ['dbEngine' => 'sqlite', 'dbPath' => BASE . '/db.sqlite'];

// Create a database service.
$databaseService = Persistence\DatabaseService($dbParams);

// Create a mapper service which depends on the databaseService.
$mapperService = new Persistence\MapperService($databaseService);

该库目前仅支持少数数据库,并且目前仅测试了sqlite。请使用以下配置与适当的驱动程序连接。

// SQLite database.
$dbParams = [
    'dbengine' => 'sqlite',
    'path' => __DIR__ . '/db.sqlite'
];

// MySQL database.
$dbParams = [
    'dbengine' => 'mysql',
    'host' => 'localhost',
    'port' => 3306,
    'dbname' => 'myDB',
    'username' => 'root',
    'password' => 'password'
];

// Postgresql database.
$dbParams = [
    'dbengine' => 'pgsql',
    'host' => 'localhost',
    'port' => 5432,
    'dbname' => 'myDB',
    'username' => 'root',
    'password' => 'password',
    'sslmode' => 'require'
];

为了清晰和避免混淆,请为您项目定义所有上述配置。有关它们含义的任何信息,请访问PDO构造的相关PHP手册页面。

保存和检索数据。

namespace myApp;

class App
{
    /**
     * Inserting into the database.
     */
    public function insert()
    {
        $mapperService = ...

        // Create a new model object for insertion.
        $myModel = MyItemModel::getNew(['userId' => 33432])
            ->setName('whatever you want.')
            ->setDescription('A great description');

        // Insert new record in the database.
        $mapperService->persist($myModel);

        if ($myModel->getId()) {
            $this->message('Record saved successfully.');
        }
    }

    /**
     * Updating the database.
     */
    public function update()
    {
        $mapperService = ...
        
        // Get a specific record from the database mapped to your model object.
        $myModel = $mapperService->getSingle(MyItemModel::class, ['id' => $form->get('item_id')]);

        // Update model with desired data. Note the setters/getters are provided out of the box by just
        // extending the baseModel which are based on the properties your model has.
        $myModel
            ->setName('whatever you want.')
            ->setDescription('A great description');

        // Update the record in the database.
        $mapperService->persist($myModel);

        // Get all MyItemModels back with the name `howdy`, order them by the id descending.
        $myItemModels = $mapperService->get(MyItemModel::class, ['name' => 'howdy'], ['id' => 'desc']);

        // Use the retrieved models somehow.
        ...
    }
}

mapper公开了databaseService,允许您执行更复杂的查询,同时将对象绑定回原始模型。考虑以下示例

namespace myApp;

use Genesis\Services\Persistence;

class SomeRepository
{
    public function getSomeItemsForPastSevenDays(Persistence\Contracts\MapperService $mapperService)
    {
        // Get the database table name based on the model.
        $table = $mapperService->getTableFromClass(Representations\Sale::class);

        // Prepare a more complex query, we can only bind objects back if we have all columns corresponding to the model.
        $query = "SELECT * FROM `{$table}` WHERE `dateSold` > (SELECT DATETIME('now', '-7 day')) AND `userId` = {$userId}";

        // Execute the query using the databaseService layer and get the data back.
        $data = $mapperService->getDatabaseService()->execute($query);

        // Bind the data to the model and return the collection.
        return $mapperService->bindToModel(Representations\Sale::class, $data);
    }
}

检索关联的模型对象

您是否注意到MyItemModel有一个userId属性,这个属性在理想世界中将链接到数据库中User表的另一个记录。如果您在应用程序中对该User进行了建模,可以使用mapper提供的getAssociated调用获取此记录。请考虑以下示例。

namespace myApp;

class ExampleGetAssociated
{
    public function getAssociatedUser()
    {
        $mapperService = ...

        // Get a random model for this example.
        $myItemModel = $mapperService->getSingle(MyItemModel::class, ['id' => 15]);

        // Get the user associated with the $myItemModel object.
        $user = $mapperService->getAssociated(User::class, $myItemModel);

        ...
    }
}

删除记录

mapper允许您以两种方式删除记录。请考虑以下示例。

namespace myApp;

use Genesis\Services\Persistence;

class App
{
    public function deleteExampleOne()
    {
        $mapperService = ...;

        // If say a delete request comes in.
        if ($this->issetGet('delete')) {
            // Get the product Id from the request.
            $productId = $this->getParam('productId');

            // Delete the record.
            $mapperService->delete(Product::class, ['id' => $productId]);
        }

        ...
    }

    // If say the product object was passed into the method.
    public function deleteExampleTwo(Product $product)
    {
        $mapperService = ...;

        // This will delete the record from the database as long as the getId() method on the object returns
        // the id of the record.
        $mapperService->delete($product);
    }
}

您可以自由探索mapperService提供的其他调用。mapper还允许您根据模型创建表。

控制台

此包包含2个控制台脚本

  1. db-setup.php {model-directory} # 根据模型类定义设置您的数据库。
  2. db-migrate.php {model-directory} # 您对模型类定义所做的任何更改都将被检测到。

这些可以在bin文件夹中找到。