如何使用上传文件(例如图像)文件设置 yaml 灯具



我想为我的symfony2项目设置夹具。我想避免PHP类,但使用yaml文件来定义夹具。仅存储文本字段和关系的实体工作正常,但我不知道是否可以以这种方式添加 UploadedFile,例如图像文件。

目前,我正在使用KhepinYamlFixtureBundle,不确定是否可以通过服务调用来定义它们,或者它是否根本没有此功能。

我会切换到提供该功能的捆绑包。

你应该使用Alice。

Alice 是一个 PHP 灯具生成器,可让您轻松地从 PHP 或 Yaml 文件加载灯具管理上传的文件。下面是一段代码,用于从 Doctrine Fixtures 类加载一些数据装置:

<?php
namespace MyProjectUserFixtures;
use DoctrineBundleFixturesBundleFixture;
use DoctrineCommonPersistenceObjectManager;
use NelmioAliceLoaderYaml;
use NelmioAliceORMDoctrine;
use SymfonyComponentFinderFinder;
class LoadUserData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        // load objects from a yaml file
        $loader = new NelmioAliceLoaderYaml();
        $objects = $loader->load(__DIR__.'/users.yml');
        $persister = new NelmioAliceORMDoctrine($manager);
        $persister->persist($objects);
        // Copy images into the legacy application
        $fs = $this->container->get('filesystem');
        $legacyPath = $this->container->getParameter('legacy_path').'/web/uploads';
        $basePath = __DIR__.'/../files';
        $finder = SymfonyComponentFinderFinder::create()
            ->files()
            ->in($basePath)
            ->ignoreDotFiles(true)
            ->ignoreVCS(true)
        ;
        foreach ($finder as $file) {
            if ($file->isFile()) {
                $newFile = str_replace($basePath, $legacyPath, $file->getPathname());
                $fs->copy($file->getPathname(), $newFile);
            }
        }
    }
}

并在您的数据中加载到YML文件中:

# users.yml
MyProjectUser:
    user_1:
        firstName: "Albert"
        lastName:  "Einstein"
        username:  "albert"
        email:     "albert.einstein@protonmail.com"

更多信息在这里。

最新更新