繁体   English   中英

(符号4)如何从非控制器类中获取项目的基本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的存储库类中获取“ http://www.yourwebsite.com ”?

之所以需要执行此操作,是因为我使用的是Liip图片服务,该服务会返回整个网址,并且我只需要相对于根目录的网址,因此,我必须删除“ 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"

我需要解析出http://www.mywebsite.com并从路径中获取/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;
    }

    ...
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM