【问题标题】:How to set up yaml fixtures with UploadedFile (e.g. image) files?如何使用 UploadedFile(例如图像)文件设置 yaml 固定装置?
【发布时间】:2014-03-10 23:03:04
【问题描述】:

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

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

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

【问题讨论】:

标签: php symfony yaml fixtures


【解决方案1】:

你应该使用Alice

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

<?php

namespace MyProject\User\Fixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Nelmio\Alice\Loader\Yaml;
use Nelmio\Alice\ORM\Doctrine;
use Symfony\Component\Finder\Finder;

class LoadUserData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        // load objects from a yaml file
        $loader = new \Nelmio\Alice\Loader\Yaml();
        $objects = $loader->load(__DIR__.'/users.yml');

        $persister = new \Nelmio\Alice\ORM\Doctrine($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 = \Symfony\Component\Finder\Finder::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
MyProject\User:
    user_1:
        firstName: "Albert"
        lastName:  "Einstein"
        username:  "albert"
        email:     "albert.einstein@protonmail.com"

更多信息here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2010-10-05
相关资源
最近更新 更多