Symfony 4, get root path directory from data fixtu

2019-08-22 04:15发布

问题:

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

The final goal :

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

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 ;) )

回答1:

Symfonfy 4.1.7

Service.yml

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

Fixtures File

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() info from https://stackoverflow.com/a/18883334/624533 (Thankyou!).

Hope this helps someone.