forci/static-data-bundle

为需要预定义实体ID的应用程序提供静态数据导入

安装量: 9,202

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 3

分支: 0

开放问题: 0

类型:symfony-bundle

v0.7.1 2023-10-22 22:52 UTC

This package is auto-updated.

Last update: 2024-09-23 00:54:01 UTC


README

composer require forci/static-data-bundle

将包添加到您的包数组中

new \Forci\Bundle\StaticData\ForciStaticDataBundle(),

配置您的包。这些是需要导入静态数据的包

forci_static_data:
    bundles:
        - App
        # Note: Your bundle can be configured as a string or full-blown config.
        # You can also specify your entity manager if not "default" or if you have many
        # For advanced usage, please refer to the Configuration file of this bundle.
        - Api
        -
           bundle: Frontend
           # Note: When looking up classes, this bundle converts slashes to namespace separators
           directory: Some/Directory
           em: some_other_em
        - Admin

静态数据包将检查每个bundle配置的目录(默认为StaticData)并选择所有的*Data.php文件。然后,如果存在ID等于FQCN的服务,或者如果该类是Forci\Bundle\StaticData\StaticData\StaticData的子类,它将被构造并添加到`Forci\Bundle\StaticData\StaticData\DataCollection`。请注意,这仅在需要时发生,并且除了加载另一个包并处理其配置外,不会减慢您应用程序的性能。

使用方法

默认情况下,您需要将静态数据文件放在BundleRootDir/StaticData中。以下是一个名为App的包的示例(请注意缺少Bundle后缀!如果您正在使用它,您需要指定配置中的完整包名,例如AppBundle)

<?php

// src/App/StaticData/RoleData.php

namespace App\StaticData;

use App\Entity\Role;
use Forci\Bundle\StaticData\StaticData\StaticData;

class RoleData extends StaticData {

    public function doLoad() {
        $records = [
            Role::ID_ADMINISTRATOR => [
                'name' => 'Administrator',
                'role' => 'ROLE_ADMIN'
            ],
            Role::ID_TRANSLATOR => [
                'name' => 'Translator',
                'role' => 'ROLE_TRANSLATOR'
            ],
        ];

        foreach ($records as $id => $role) {
            if (!$this->find(Role::class, $id)) {
                $entity = new Role();
                $entity->setId($id);
                $entity->setName($role['name']);
                $entity->setRole($role['role']);
                $this->persist($entity);
            }
        }
    }
}

您需要做的就是运行./bin/console forci_static_data:load命令。您还可以将此命令添加到您的部署流程中。这样,添加新的静态实体就变得非常简单。这对于多个开发者在多个不同的分支上开发,并且您希望保持迁移干净的情况非常有用。在多个分支上执行重构通常会导致在部署到生产环境时由于DoctrineMigrationsBundle的工作方式而出现意外的崩溃。

如果您只想导入一个包的静态数据,请运行./bin/console forci_static_data:load -b YourBundle./bin/console forci_static_data:load --bundle=YourBundle

高级使用

此包注册了两个服务

  • forci_static_data.data_finder - Forci\Bundle\StaticData\StaticData\DataFinder的实例
  • forci_static_data.data_loader - Forci\Bundle\StaticData\StaticData\DataLoader的实例

您可以使用这些服务以任何您希望的方式查找和/或加载您的静态数据 - 您可以将它们嵌入到您自己的命令中。