Symfony2的。为设置cookie和重定向创建服务

时间:2014-12-24 18:20:46

标签: php symfony cookies

我接下来的任务:禁止每1分钟更多地创建新邮件。接下来是逻辑。当用户提交表单时,将创建cookie,生命周期为60秒。然后当用户再次尝试提交时,我会检查cookie是否存在。如果为true - 将用户重定向到主页面。如果为false - 创建消息,持久保存到数据库中,创建cookie。所以我在我的控制器中创建了下一个Action:

namespace Faster\Bundle\MessageBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Faster\Bundle\MessageBundle\Entity\Message;
use Faster\Bundle\MessageBundle\Form\MessageType;

class MessageController extends Controller
{
...
public function createAction(Request $request)
    {
        $message = new Message();
        $form = $this->createCreateForm($message);
        $form->handleRequest($request);
        if ($form->isValid()) {
            $valueOfCookiePerMinute = $request->cookies->get('perMinute');
            if ($valueOfCookieName) {

                return $this->redirect($this->generateUrl('message'));
            }
            else {
                $cookie = new Cookie('perMinute', 'CookieIsAlreadyExist', time() + 60);
                $response = new RedirectResponse($this->generateUrl('message'));
                $response->headers->setCookie($cookie);
                $em = $this->getDoctrine()->getManager();
                $em->persist($message);
                $em->flush();

                return $response;
            }
        }
...
}

但我认为这是胖控制器。我认为它可以为这部分代码实现服务:

$valueOfCookiePerMinute = $request->cookies->get('perMinute');

if ($valueOfCookieName) {

                return $this->redirect($this->generateUrl('message'));
            }
            else {
                $cookie = new Cookie('perMinute', 'CookieIsAlreadyExist', time() + 60);
                $response = new RedirectResponse($this->generateUrl('message'));
                $response->headers->setCookie($cookie);
                $em = $this->getDoctrine()->getManager();
                $em->persist($message);
                $em->flush();

                return $response;
            }

但我很难接受这样的服务。我无法理解我是如何做到的/ 请帮我实现和理解它 谢谢

1 个答案:

答案 0 :(得分:1)

你是对的,你的控制器应该是一个外观,所以在服务中设置这个代码是个好主意。

首先,创建一个类:

// Messaging/MessageTimer.php

namespace Faster\Bundle\MessageBundle\Messaging;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Routing\RouterInterface;
use Doctrine\Common\Persistence\ManagerRegistry;

class MessageTimer implements MessageTimerInterface
{
    /**
     * The database object manager.
     *
     * @var Doctrine\Common\Persistence\ObjectManager
     */
    private $objectManager;

    /**
     * The router.
     *
     * @var RouterInterface
     */
    private $router;

    /**
     * Constructor.
     *
     * @param ManagerRegistry $managerRegistry The manager registry.
     */
    public function __construct(
        ManagerRegistry $managerRegistry,
        RouterInterface $router
    )
    {
        $this->objectManager = $managerRegistry->getManager();
        $this->router = $router;
    }

    /**
     * {@inheritdoc}
     */
    public function processRequest(Request $request)
    {
        $valueOfCookiePerMinute = $request->cookies->get('perMinute');

        if ($valueOfCookieName) {
            return new RedirectResponse($this->router->generate('message'));
        } else {
            $cookie = new Cookie('perMinute', 'CookieIsAlreadyExist', time() + 60);
            $response = new RedirectResponse($this->router->generate('message'));
            $response->headers->setCookie($cookie);
            $this->objectManager->persist($message);
            $this->objectManager->flush();

            return $response;
        }
    }
}

正如您所看到的,我们使用一个接口来使用低耦合(您将能够轻松地替换此类的实现以及服务)。这对于充分利用依赖注入至关重要!

// Messaging/MessageTimerInterface.php

namespace Faster\Bundle\MessageBundle\Messaging;

use Symfony\Component\HttpFoundation\Request;

interface MessageTimerInterface
{
    /**
     * Process a request.
     *
     * @param Request $request The request.
     */
    public function processRequest(Request $request);
}

然后,你必须在这个类上声明一个服务:

# Resources/config/services.yml

parameters:
    your_own.message_timer.class: Faster\Bundle\MessageBundle\Messaging\MessageTimer

services:
    your_own.message_timer:
        class: %your_own.message_timer.class%
        arguments: [@doctrine, @router]

最后,您只需在控制器中使用它:

namespace Faster\Bundle\MessageBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Faster\Bundle\MessageBundle\Entity\Message;
use Faster\Bundle\MessageBundle\Form\MessageType;

class MessageController extends Controller
{
    // ...

    public function createAction(Request $request)
    {
        $message = new Message();
        $form = $this->createCreateForm($message);
        $form->handleRequest($request);
        if ($form->isValid()) {
            return $this->get('your_own.message_timer').processRequest($request);
        }

    // ...
}