首页 > 解决方案 > (Symfony 4)如何从非控制器类中获取项目的基本 URI(http://www.yourwebsite.com/)?

问题描述

如何从 Symfony 4 的存储库类中获取“ http://www.yourwebsite.com ”?

我需要这样做的原因是因为我使用的是返回整个 url 的 Liip 图像服务,而我只需要相对于 root 的 url,所以我必须去掉“ http://www.yourwebsite .com " 来自返回的路径。

我使用了 KernelInterface,它只返回你机器中的路径(即你机器中的 var/www/...)。

我已经尝试注入 http 基金会的 Request 对象,这样我就可以调用 getPathInfo() 方法,这是我的存储库类中的内容:

use Symfony\Component\HttpFoundation\Request;

class PhotoRepository extends ServiceEntityRepository
{ 
    /**
     * @var Request
     */
    protected $request;

    public function __construct(Request $request){
        $this->request = $request;
    }

但我只是得到错误Cannot autowire service "App\Repository\PhotoRepository": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.

这是我的 services.yaml 中“服务”下的内容:

App\Repository\PhotoRepository:
    arguments:
        - Symfony\Component\HttpFoundation\Request  

这是我生成的文件的完整路径:

"http://www.mywebsite.com/media/cache/my_thumb/tmp/phpNbEjUt"

我需要解析 get thehttp://www.mywebsite.com/media/cache/my_thumb/tmp/phpNbEjUt从路径中获取。

标签: symfonyuribase

解决方案


正如 Cerad 已经在评论中所写,您可以注入Symfony\Component\HttpFoundation\RequestStack

App\Repository\PhotoRepository:
    arguments:
        - Symfony\Component\HttpFoundation\RequestStack
        - Doctrine\Common\Persistence\ManagerRegistry

PhotoRepository 的构造函数将如下所示:

class PhotoRepository extends ServiceEntityRepository
{ 
    /**
     * @var RequestStack
     */
    protected $requestStack;

    public function __construct(RequestStack $requestStack, ManagerRegistry $managerRegistry)
    {
        parent::__construct($managerRegistry, Photo::class);

        $this->requestStack = $requestStack;
    }

    ...
}

然后,您可以使用以下方式确定当前 URL:

private function getCurrentUrl(): string
{
    $request = $this->requestStack->getCurrentRequest();

    return $request->getBaseUrl(); // or possibly getUri()
}

推荐阅读