douhuai2015 2016-02-02 11:47
浏览 56
已采纳

从控制器和twig模板获取图像文件夹URI

I moved all the public images of my website to a folder out of the web folder of symfony so it can be shared with other web applications. I created a symbolic link to this folder so it can be accessed from the web folder of the symfony application.

ln -s /absolute/path/to/images /path/to/symfony/application_01/web/images
ln -s /absolute/path/to/images /path/to/symfony/application_02/web/images

Etc... for all applications.

I'm looking for a method that would allow me to retrieve the images URI in my development environment on localhost as well as in my production environment on the remote web server.

I would like to be able to retrieve this URI from the twig template AND from the controller.

Basically (for my application_01 for instance):

In the development environment it would return:

http://localhost/images/my_image.jpg

In the production environment, it would return:

http://www.application_01.com/images/my_image.jpg

My problem is that I found lots of different ways to get URIs but I'm not totally clear about how Symfony manages them and what functions to use to have a global solution working in all cases.

What is the best way to achieve my goal?


EDIT

Specifically I found some SO answers to quite similar questions proposing to use the following functions:

$request->getScheme(); $request->getHttpHost();

That seems to correspond to the values or superglobals $_SERVER['REQUEST_SCHEME'] and $_SERVER['HTTP_HOST']

And I don't know if this is the proper way to get this information since this is linked to the current request received by the server.

Isn't there another way to get this info independently from the request currently processed by the server?

  • 写回答

1条回答 默认 最新

  • dpfwhb7470 2016-02-02 12:11
    关注

    Define the following url

    image_url: path: /images/{image}

    Then use it like this

    /** @var Router $router */
    $router = $this->get('router');
    $url = $router->generate('image_url', ['image' => 'my_image.jpg'], Router::ABSOLUTE_URL);
    

    $url now contains the absolute url to your image. And of course it's the best practice you can think of :)

    ----- Answer to your comment about app_dev.php We used this solution in our company months ago.

        preg_replace('#/(.+?)\.php)', '', $router->generate('my_url');
    

    http://techimho.com/index.php/2015/10/15/generate-production-url-in-dev-environment/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部