我有一个简单的 Doctrine Entity,我必须在其中处理文件上传。我已经按照 Symfony 的建议来实现这个实体(参见http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html),所以我有一个看起来像这样的实体(简化):
<?php
// src/Acme/DemoBundle/Entity/Document.php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*/
class Document
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank
*/
public $name;
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
}
我想更进一步,在 Symfony 配置文件中配置上传目录,如下所示:
parameters:
upload_dir: new_upload_dir_value
然后在我的实体中使用这个配置值,而不是:
- 根据
getUploadRootDir
方法中的当前文件猜测上传目录(如果我更改实体文件位置会发生什么?) - 将
"uploads"
字符串直接放入getUploadDir
方法中(我希望能够随时更改它的名称)
我是 Symfony2 的新手,所以也许我没有正确的方法来处理这种情况,但是有没有人知道一种没有太多缺点的好方法来处理这个问题?