为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据用户角色对同一路由使用不同的控制器?

如何根据用户角色对同一路由使用不同的控制器?

PHP
白衣染霜花 2022-10-09 17:20:05
我正在尝试实现多个控制器来监听一个路由/account。有两个控制器,并且只有一个应该在选择位于用户角色范围内的 URL 上执行。namespace AppBundle\Controller;use AppBundle\Entity\Role;use Symfony\Bundle\FrameworkBundle\Controller\Controller;use Symfony\Component\Routing\Annotation\Route;/** * @Route("/account") */abstract class DashboardController extends Controller{    protected $userRoles;    public function __construct()    {        $this->userRoles = $this->getUser()->getRoles();    }    /**     * Get all user roles     */    public function getRoles()    {        return $this->userRoles;    }    /**     * Get user account type     *     * @return Role     */    public function getAccountType(): Role    {        $accountType = new Role();        foreach ($this->userRoles as $role) {            if(Role::ROLE_STUDENT == $role->getName()) {                $accountType = $role;            } else if(Role::ROLE_SCHOOL_REPRESENTATIVE == $role->getName()) {                $accountType = $role;            } else if(Role::ROLE_EMPLOYER == $role->getName()) {                $accountType = $role;            } else if(Role::ROLE_ADMIN == $role->getName()) {                $accountType = $role;            }        }        return $accountType;    }}namespace AppBundle\Controller;class CompanyDashboardController extends DashboardController{    public function __construct()    {        parent::__construct();    }    /**     * @Route("/", name="dashboard_company_home", methods={"GET"})     * @return Response     */    public function index()    {        return $this->render('dashboard/company/index.html.twig');    }}namespace AppBundle\Controller;class AdminDashboardController extends DashboardController{    public function __construct()    {        parent::__construct();    }    /**     * @Route("/", name="dashboard_admin_home", methods={"GET"})     * @return Response     */    public function index()    {        return $this->render('dashboard/admin/index.html.twig');    }}这就是我到目前为止所得到的。
查看完整描述

1 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您不能使用“路由”声明执行此操作,因为路由侦听器的执行优先级高于安全侦听器。两者都发生在KernelEvents::REQUEST事件期间,但路由出现在防火墙之前。

当解析到控制器映射的路由时,您还没有用户信息(这就是为什么您不能简单地附加另一个侦听器并将用户信息注入Request对象,因此它可以在路由声明中用于表达式匹配,例如)。

基本上,一条路线,一个控制器。如果您想为这些用户提供不同的逻辑,则必须在进入控制器后应用它。


查看完整回答
反对 回复 2022-10-09
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信