FosUserBundle控制器覆盖

时间:2018-04-08 14:29:01

标签: symfony controller fosuserbundle

[设置]

[问题]

在阅读有关how to override any part if a bundle的Symfony文档时, 我遇到了这些问题:

  

如果控制器是服务,请参阅下一节有关如何覆盖它的部分。否则,使用与要覆盖的控制器关联的相同路径定义新路由+控制器(并确保在捆绑之前加载新路由)。

在某些最重要的部分,看到文档仍然像以前一样不完整,感到非常高兴...对,这部分没有代码示例,甚至无法确定要做什么。

有人会非常友好地举例说明如何覆盖FosUserBundle吗?像登录部分这样的一个部分就足够了。因为相同的逻辑将适用于其他部分。

另外,作为一个问题:

  • 是否值得使用FosUserBundle?
  • 是否比FosUserBundle更容易使用?
  • 制作我自己的处理登录的逻辑不是更值得和更快吗?

1 个答案:

答案 0 :(得分:1)

我的理解:只需创建您的控制器,然后在您的配置中添加一个路径,其路径与您要覆盖的路径相同,确保它之前已加载。

例如,要覆盖登录操作:

// AppBundle\Controller\UserController.php

/**
 * @route("/login", name="login_override")
 * @param Request $request
 * @return Response
 */
public function loginAction(Request $request)
{
    /** @var $session Session */
    $session = $request->getSession();

    $authErrorKey = Security::AUTHENTICATION_ERROR;
    $lastUsernameKey = Security::LAST_USERNAME;

    // get the error if any (works with forward and redirect -- see below)
    if ($request->attributes->has($authErrorKey)) {
        $error = $request->attributes->get($authErrorKey);
    } elseif (null !== $session && $session->has($authErrorKey)) {
        $error = $session->get($authErrorKey);
        $session->remove($authErrorKey);
    } else {
        $error = null;
    }

    if (!$error instanceof AuthenticationException) {
        $error = null; // The value does not come from the security component.
    }

    // last username entered by the user
    $lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);

    $tokenManager = $this->container->get('security.csrf.token_manager');

    $csrfToken = $tokenManager
        ? $tokenManager->getToken('authenticate')->getValue()
        : null;

    return $this->render('@FOSUser/Security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error' => $error,
        'csrf_token' => $csrfToken,
    ));
}


#app\config\routing.yml
app:
    resource: '@AppBundle/Controller/'
    type: annotation

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"
相关问题