如何从Symfony 4中的存储库类中获取“http://www.yourwebsite.com”?
我需要这样做的原因是因为我使用Liip图像服务返回整个url,我只需要相对于root的url,所以我必须从返回的路径中去掉“http://www.yourwebsite.com”。
我使用了KernelInterface,它只返回机器内的路径(即机器中的var / www / ...)。
我已经尝试过注入http foundation的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;
}
...
}
然后,您可以使用以下内容确定当前URL:
private function getCurrentUrl(): string
{
$request = $this->requestStack->getCurrentRequest();
return $request->getBaseUrl(); // or possibly getUri()
}