php - 从子函数返回重定向
问题描述
我正在做一个 Symfony 项目。它设置了自定义访问控制(动态创建并存储在数据库中)。因此,我创建了一个自定义 BaseController 类,它允许我执行单行调用来验证访问。这是其中的一些代码:
class BaseController extends AbstractController
{
function prepare($customer, $product, $right) {
// These are all defined in the class.
$this->loadCompany($customer);
$this->canAccessProduct($product);
$this->checkAccessRights($customer, $product, $right);
}
}
prepare 方法在每个控制器的顶部调用。例如:
class IndexController extends BaseController {
/**
* @Route("/{customer}/download",
* name="download_home")
*/
function customerIndex($customer)
{
$this->prepare($customer, "download", "read");
}
}
现在这是我要进行的更改:我想从路由中删除 {customer} 并将其作为“准备”函数调用的一部分加载。因此,我想将客户存储在会话变量中。如果未设置会话变量,我想重定向到不同的控制器。这是在 Symfony 中使用return $this->redirectToRoute("app_company_select")
. 那么我可以设置它,以便在$this->prepare()
其中返回控制器函数的返回调用吗?
我已经尝试过parent::return()
,但这给出了一个未知的功能错误。还有另一种方法可以做到这一点吗?
解决方案
然后只需从您所在的位置重定向即可。只要您还没有发送任何标题,这应该可以正常工作。
public function prepare(...)
{
$hasAccess = false
// Check for access
if(!$hasAccess){
(new RedirectResponse('/go/somewhere'))->send();
exit;
}
}
推荐阅读
- c++ - Lua SWIG 基础知识
- ios - 如何在 swift 3 中通过授权访问 AWS API 网关?
- spring-mvc - 如何配置 spring-servlet.xml 以纠正 Spring-MVC 3.0 项目的注入失败?
- powershell - 即使没有返回错误,也无法通过 powershell 脚本远程安装 chrome
- sonarjs - 在 SonarJS 中针对特定文件提出问题
- asp.net - 对 ID 超过 32768 的 ASP.NET SQL Server 查询的错误请求
- c++ - 强制子类中的每个方法调用特定的父类方法
- mongodb - mongodb-nodejs-driver,DeprecationWarning:collection.count 已弃用
- python - 使用 Kaggle CLI 时出错
- javascript - 从孩子改变父母的状态时,为什么父母不再渲染?