亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何根據用戶角色對同一路由使用不同的控制器?

如何根據用戶角色對同一路由使用不同的控制器?

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 關注
  • 99 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號