(Symfony 4) 如何从非控制器 class 中获取项目的基本 URI (http://www.yourwebsite.com/)?

(Symfony 4) How can I get the base URI of my project (the http://www.yourwebsite.com/) from within a non-controller class?

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

我需要这样做的原因是因为我正在使用 returns 整个 url 的 Liip 图像服务,而我只需要 url 相对于root,所以我必须从返回的路径中删除“http://www.yourwebsite.com”。

我使用了 KernelInterface 并且只有 returns 来自您机器内部的路径(即您机器中的 var/www/...)。

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

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 中 "services" 下的内容:

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

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

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

我需要解析出 <a href="http://www.mywebsite.com" rel="nofollow noreferrer">http://www.mywebsite.com</a> 并从路径中获取 /media/cache/my_thumb/tmp/phpNbEjUt

正如 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()
}