數據夾具基本Symfony的3個應用程序具有VichUploader bundle安裝和配置,用於上傳文件對一個實體。與VichUploader束在Symfony3
如何將文件附加到這個實體在我的ORM數據燈具?
有一個question for this problem in Symfony 2我試過這段代碼。夾具加載沒有錯誤,但「上傳」的文件不會複製到最終目的地。
我可以手動做到這一點,我的最新嘗試是這樣的:
<?php
// src/AppBundle/DataFixtures/ORM/LoadCourseData.php
namespace AppBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use AppBundle\Entity\Course;
class LoadCourseData extends AbstractFixture implements OrderedFixtureInterface
{
public function load(ObjectManager $manager)
{
$course = new Course();
$course->setName('How to make data fixtures in Symfony lol')
->setAuthor($this->getReference('admin-user'))
->setSummary('You\'ll know when I know!')
->setLicense($this->getReference('cc-by'))
->setDifficulty(1);
// Persist to generate slug (to be used for uploads)
$manager->persist($course);
// Attach file
// I copy it to a temporary directory as per the Symfony2 answer
copy(__DIR__.'/../Files/kitten.jpg', '/tmp/kitten.jpg');
// These are filled in for completeness
$mimetype = MimeTypeGuesser::getInstance()->guess('/tmp/kitten.jpg');
$size = filesize('/tmp/kitten.jpg');
// Create a new UploadedFile
$file = new UploadedFile('/tmp/kitten.jpg', 'kitten.jpg', $mimetype, $size, null, true);
// I have to move it manually?
// Plus how can I take advantage of the VichUploader namer?
$file->move(__DIR__.'/../../../../web/img/upload/course/');
// Apply to entity
$course->setImageFile($file);
// Persist
$manager->persist($course);
$manager->flush();
}
public function getOrder()
{
return 4;
}
}
我的解決方案仍然需要大量的工作!我吠叫錯了樹嗎?
- 上傳路徑已在
config.yml
中定義。我應該在那裏訪問,或將其轉換爲參數 - 需要更多的錯誤檢查和異常拋出
- 將文件複製到目標,但文件名是錯誤的,因爲它不使用配置VichUploader命名器
- 它應該住在其他地方,可能作爲一種服務?