symfony - (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
从路径中获取。
解决方案
正如 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()
}
推荐阅读
- c# - 用户单击 ASP.NET Web 表单上的按钮与计时器运行调用相同按钮单击事件的方法之间的区别?
- c - 理解c中不同风格的#defines
- node.js - $lookup 中用于比较 objectId 的 mongodb $match 操作未按预期工作
- ios - 如何在免费试用期内提出 IAP 购买请求?
- python - Python是否可以用pygame调用pickfile窗口?
- html - 如何摆脱包装器周围的空间
- django-rest-framework - 尝试获取序列化程序“DialogSerializer”上字段“对手”的值时出现 AttributeError
- f# - 使用 XmlProvider 的 EmbeddedResource 选项时缺少根元素
- python - 如何将“pandas”数据帧和“numpy”数组合并到 H5 中
- c# - 创建用户时如何修复 System.ObjectDisposedException