首页 > 解决方案 > 从子函数返回重定向

问题描述

我正在做一个 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(),但这给出了一个未知的功能错误。还有另一种方法可以做到这一点吗?

标签: phpsymfonysymfony4

解决方案


然后只需从您所在的位置重定向即可。只要您还没有发送任何标题,这应该可以正常工作。

public function prepare(...)
{
    $hasAccess = false
    // Check for access
    if(!$hasAccess){
        (new RedirectResponse('/go/somewhere'))->send();
        exit;
    }
}

推荐阅读