Symfony 4,从数据夹具类获取根路径目录 [英] Symfony 4, get root path directory from data fixture Class

查看:21
本文介绍了Symfony 4,从数据夹具类获取根路径目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Symfony 4 项目中,是否有一种正确的/symfony 方法可以从 Fixture 类中获取根路径目录?

From a Symfony 4 project, Is there a properly/symfony way for get the root path directory from a Fixture class ?

最终目标:

当我部署我的网站时,我使用fixtures 类在我的数据库中加载一些默认"数据.(可能这不是一个好习惯)

I use fixtures class for load some "default" datas in my database when I deploy my website. (May be its not a good practice)

在这些默认数据中,我需要存储项目的根路径目录,因为我需要来自项目中自定义 utils 和服务类的这些信息.

Among theses defaults datas, I need to store the root path directory of the project because I need this information from custom utils and services class in the project.

我知道有多种方法可以做到这一点.目前,我对绝对路径进行了硬编码( <= 有史以来最丑陋的方式;))

I know there are multiple ways for that. Currently, I hard coded the absolute path ( <= best ugliest way ever ;) )

推荐答案

Symfonfy 4.1.7

Service.yml

services:
  _defaults:
    bind:
      $webDirectory:  '%kernel.project_dir%/public_html/'

灯具文件

use Symfony\Component\HttpFoundation\File\UploadedFile;
// --
private $webDirectory, $imageLocation;
public function __construct($webDirectory)
{
    $this->webDirectory = $webDirectory;
    $this->imageLocation = $webDirectory . 'img/config/';
}
public function load(ObjectManager $manager){
    for ($i = 0; $i < 20; $i++) {
        copy($this->imageLocation . 'blog_default_50x50.jpg', $this->imageLocation . 'blog_default_50x50-copy.jpg');
        $file = new UploadedFile($this->imageLocation . 'blog_default_50x50-copy.jpg', 'Image1', null, null, null, true);
        ---
        $blogPost->setFile($file);
        $manager->persist($blogPost);
    }
    $manager->flush();
}

UploadedFile() 信息来自 https://stackoverflow.com/a/18883334/624533(谢谢!).

UploadedFile() info from https://stackoverflow.com/a/18883334/624533 (Thankyou!).

希望这对某人有所帮助.

Hope this helps someone.

这篇关于Symfony 4,从数据夹具类获取根路径目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆