Symfony2 FOSUserBundle重写控制器(Controllers)

  1. 创建一个子Bundle,继承FOSUserBundle,
    // src/Acme/UserBundle/AcmeUserBundle.php
    <?php
    
    namespace Acme\UserBundle;
    
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    
    class AcmeUserBundle extends Bundle
    {
        public function getParent()
        {
            return 'FOSUserBundle';
        }
    }
     * Symfony2框架只允许一个Bundle有一个子Bundle,无法再创建FOSUserBundle的子Bundle。
  2. 创建一个和FOSUserBundle相同名字的Controller,一种方式继承父Bundle的Controller,继承的话,不需要把父Controller的所有方法重写,如下:
    <?php
    // src/Acme/UserBundle/Controller/RegistrationController.php
    namespace Acme\UserBundle\Controller;
    
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use FOS\UserBundle\Controller\RegistrationController as BaseController;
    
    class RegistrationController extends BaseController
    {
        public function registerAction()
        {
            $form = $this->container->get('fos_user.registration.form');
            $formHandler = $this->container->get('fos_user.registration.form.handler');
            $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
    
            $process = $formHandler->process($confirmationEnabled);
            if ($process) {
                $user = $form->getData();
    
                /*****************************************************
                 * Add new functionality (e.g. log the registration) *
                 *****************************************************/
                $this->container->get('logger')->info(
                    sprintf('New user registration: %s', $user)
                );
    
                if ($confirmationEnabled) {
                    $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
                    $route = 'fos_user_registration_check_email';
                } else {
                    $this->authenticateUser($user);
                    $route = 'fos_user_registration_confirmed';
                }
    
                $this->setFlash('fos_user_success', 'registration.flash.user_created');
                $url = $this->container->get('router')->generate($route);
    
                return new RedirectResponse($url);
            }
    
            return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
                'form' => $form->createView(),
            ));
        }
    }
    * 如果不想继承FOSUserBundle的Controller类,可以直接定义一个Controller,但需要把FOSUserBundle的所有方法全部重写。

猜你喜欢

转载自linleizi.iteye.com/blog/2121665