如何从实体内部获取网络目录路径

如何从实体内部获取网络目录路径

本文介绍了如何从实体内部获取网络目录路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了 如何使用 Doctrine 处理文件上传 和我不想对 __DIR__.'/../../../../web/'.$this->getUploadDir(); 路径进行硬编码,因为可能在将来我将更改 web/ 目录.怎么做更灵活?我发现了这个但是它没有回答如何从实体内部更灵活地做到这一点

I researched the How to Handle File Uploads with Doctrine and I don't want to hard-code the __DIR__.'/../../../../web/'.$this->getUploadDir(); path because maybe in future I will change the web/ directory. How to do it more flexible? I found this but it doesn't answer the question how to do it more flexible from inside the Entity

推荐答案

此处不应使用实体类作为表单模型.根本不适合那份工作.如果实体具有 path 属性,则它可以存储的唯一有效值是:null(如果缺少文件)和表示文件路径的字符串.

You shouldn't use entity class as a form model here. It's simply not suitable for that job. If the entity has the path property, the only valid values it can stores are: null (in case lack of the file) and string representing the path to the file.

  1. 创建一个单独的类,它将成为您表单的模型:

  1. Create a separate class, that's gonna be a model for your form:

class MyFormModel {
     /** @Assert\File */
     private $file;

     /** @Assert\Valid */
     private $entity;

     // constructor, getters, setters, other methods
}

  • 在您的表单处理程序(通过 DIC 配置的单独对象;推荐)或控制器中:

  • In your form handler (separate object configured through DIC; recommended) or the controller:

    ...
    if ($form->isValid()) {
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile */
        $file   = $form->getData()->getFile();
    
        /** @var \Your\Entity\Class */
        $entity = $form->getData()->getEntity();
    
        // move the file
        // $path = '/path/to/the/moved/file';
    
        $entity->setPath($path);
    
        $someEntityManager->persist($entity);
    
        return ...;
    }
    ...
    

  • 在表单处理程序/控制器中,您可以从 DIC 访问任何依赖项/属性(包括上传目录的路径).

    Inside form handler/controller you can access any dependencies/properties from DIC (including path to the upload directory).

    您链接的教程有效,但它是糟糕设计的一个例子.实体不应知道文件上传.

    The tutorial you've linked works, but it's an example of bad design. The entities should not be aware of file upload.

    这篇关于如何从实体内部获取网络目录路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-26 13:24