VichUploader uri_prefix 不考虑环境

VichUploader uri_prefix not accounting for environment

我在我的项目中使用 VichUploaderBundle
考虑到环境(特别是 dev),我无法下载 link(使用 vich_file 表单类型时)。我想这样做,因为我想通过一个函数来路由下载函数。

我的配置是这样的;

vich_uploader:
    db_driver: orm
    twig:      true
    mappings:
        logo_image:
            uri_prefix:         /foo/image
            upload_destination: %kernel.root_dir%/../app/private/images
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

这会生成 http://example.com/foo/image/fubar.jpg 的下载 uri,与环境无关。
在开发环境中应该是 http://example.com/app_dev.php/foo/image/fubar.jpg,或者在测试环境中 http://example.com/app_test.php/foo/image/fubar.jpg

一个可能的解决方案是使用可以访问路由器 class 的自定义文件命名器 class。 在配置中将 uri_prefix 设置为 /

vich_uploader:
    db_driver: orm
    twig:      true
    mappings:
        logo_image:
            uri_prefix:         /
            upload_destination: %kernel.root_dir%/../app/private/images
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
            namer: my.namer.foo

创建一个服务命​​名器 class return 完整 url 和所需的路由(带参数);

<?php
namespace AppBundle\Service;

use Vich\UploaderBundle\Naming\NamerInterface,
    Vich\UploaderBundle\Mapping\PropertyMapping;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class MyNamer implements NamerInterface 
{

    private $router;

    public function __construct(Router $router) 
    {
        $this->router = $router;
    }

    public function name($foo, PropertyMapping $mapping) 
    {
        $router = $this->router->getContext();
        $full_url = $router->getHost();
        $full_url .= $router->getBaseUrl().'/';
        $full_url .= 'foo/logo/'.strtolower($foo->getName());
        return $full_url;
    }

}

将其注册为服务;

services:
    my.namer.foo:
        class: AppBundle\Service\MyNamer
        arguments: ['@router']
        tags:
            - { name: namer }