symfony存储库逻辑函数

时间:2017-09-05 16:36:59

标签: php symfony repository

您好我看了很多教程,但仍然不知道如何在我已经完成的存储库中创建自定义函数。

这是我的CommentController的内容:

public function newAction(Request $request, $productId)
{
    $comment = new Comment();
    $form = $this->formFactory->create(CommentForm::class, $comment);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $em = $this->get('doctrine')->getManager();
        /** @var Product $product */
        $product = $em->getRepository(Product::class)->find($productId);

        $comment->setAuthor($this->tokenStorsge->getToken()->getUser());
        $comment->setProduct($product);
        $comment->setContent($form->get('content')->getData());

        $this->em->persist($comment);
        $this->em->flush();

    }

    return $this->render(':form:comment.html.twig', array(
        'form' => $form->createView(),
    ));
}

我只想制作一些功能,使控制器更美观?如果你给我和示例我如何通过自定义存储库功能将我的数据插入数据库。我知道如何进行自定义查询。每个帮助/想法都非常有用!

1 个答案:

答案 0 :(得分:1)

来自here

  

Doctrine 2 ORM不支持DQLDQL query builder INSERT。有关完整语法,请选中the EBNF of DQL

如果你希望你的控制器看起来更漂亮一点,你可以添加更多的抽象,从头到尾(在Symfony 2.8中有效):

BaseController.php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

abstract class BaseController extends Controller
{
    /**
     * @return ProductRepository
     */
    protected function getProductRepo()
    {
        return $this->get('doctrine.orm.entity_manager')->getRepository(Product::class);
    }
}

CommentController.php: 使用本机控制器功能创建表单并获取当前登录的用户。如果您不打算在$form->isSubmitted()$form->isValid()之间添加更复杂的逻辑,请仅使用$form->isValid()

class CommentController extends BaseController
{
    public function newAction(Request $request, $productId)
    {
        $comment = new Comment();

        $form = $this->createForm(CommentForm::class, $comment);
        $form->handleRequest($request);

        if ($form->isValid()) {
            /** @var Product $product */
            $product = $this->getProductRepo()->find($productId);

            $comment->setAuthor($this->getUser());
            $comment->setProduct($product);
            $comment->setContent($form->get('content')->getData());

            $this->em->persist($comment);
            $this->em->flush();

        }

        return $this->render(':form:comment.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}