如何将单个操作分成单独的功能

时间:2017-07-07 20:30:44

标签: php symfony

我是PHP& Symfony的。我创造了同样的行动。 现在我还不知道如何将各个动作分成不同的功能。 在Symfony 3 / PHP 7.1上运行。

<?php
// AppBundle/Controller/SuccessMYController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Entity\SuccessMY;
use AppBundle\Form\SuccessMYType;

/**
 * @Route("/success")
 *
 */
class SuccessMYController extends Controller
{
   /**
     *
     * @Route("/new/{idTask}",
     *     name = "MY_success_new")
     */
    public function newSuccessAction( Request $request, $idTask )
    {
        if ( !$this -> get( 'security.authorization_checker' ) -> isGranted( 'IS_AUTHENTICATED_FULLY' ) ) {
            throw $this -> createAccessDeniedException();
        }
        $user1 = $this -> get( 'security.token_storage' ) -> getToken() -> getUser() -> getId();


        // (1) load TASK data for a new Success
        $em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );
        $taskData = $em
            -> findOneBy( [ 'id' => $idTask ] );


        // (2) create fefault data
        $newSuccess = new SuccessMY();
        $newSuccess
            -> setUserID( $user1 )
            -> setEndTask( false );


        // (3) display form
        $form = $this -> createForm( SuccessMYType::class, $newSuccess );
        $form -> handleRequest( $request ) -> getData( $newSuccess );


        // **********************************************
        // (4) save after submit
        if ( $form -> isSubmitted() && $form->isValid() ) {

            // (4.5.1) The content of the confirmation message
            $messageFrom = $this -> get( 'translator' ) -> trans( 'success.created' );

            // Data update newSuccess
            // (4.5.2) Date assignment
            $successNewDate = new \DateTime();
            $newSuccess
                -> setDateSuccess( $successNewDate );
            $successNewDate = $newSuccess -> getDateSuccess() -> format( 'Y-m-d H:i:s' );


            // (4.6.1)  Increase the number
            $taskData
                -> setOwnCount( $taskData -> getOwnCount() + 1 );

            // (4.6.3)  TASK Setting status
            if ( $newSuccess -> getEndTask() == true ) {
                $taskData
                    -> setStatusTask( 8 );
                $messageTask = $this -> get( 'translator' ) -> trans( 'task.status.succeed' );
                $messageFrom = $messageFrom . ' ' . $messageTask;
            }


            // **** (4.8) Activities in the database *****
            // (4.8.1) Save newly created database success
            $em2 = $this -> getDoctrine() -> getManager();
            $em2 -> persist( $newSuccess );
            $em2 -> flush();

            // (4.8.2) Query updating overrides Task with newSuccess
            $sql
                = "UPDATE task_MY t
                    INNER JOIN zz_tech_parent e
                        on t.id = e.idParent
                    SET
                        t.success_count = t.success_count + 1
                    WHERE
                        e.idTask =  :parTaskId";
            $params = [
                'parTaskId'      => $idTask,
            ];

            $em4 = $this -> getDoctrine() -> getManager();
            $phrase = $em4 -> getConnection() -> prepare( $sql );
            $phrase -> execute( $params );


            // (4.9) Return to task list
            // And a message about the success of the operation
            $this -> get( 'session' ) -> getFlashBag() -> add( 'msg', $messageFrom );

            return
                $this -> redirect( $this -> generateUrl( 'MY_tasks_all' ) );
        }

        // (5) For bad data return to form
        return $this -> render( 'EinsteMYBundle:SuccessMY:newSuccess.html.twig',
                                [
                                    'form'     => $form -> createView(),
                                    'taskData' => $taskData,
                                ]
        );
    }

    // (...)
}   

在哪里可以找到如何将代码发送到类似功能的示例? 应该(最好)分开哪些活动,以便在添加新活动时编码尽可能透明? 有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

很少有想法:

1)将您的表单处理内容移至Controller下的单独方法。将您的实体(SuccessMY)和Request个对象作为参数传递并返回$form->createView()

...

public function processForm(SuccessMY $successMy, request $request){

    $form = $this -> createForm( SuccessMYType::class, $newSuccess );
    $form -> handleRequest( $request ) -> getData( $newSuccess );

    ...

    return $form->createView();

}

...

2)键入您的$idTask并将其重命名为$task - 如果存在,Symfony会为您加载该实体。

 public function newSuccessAction( Request $request, !YOUR_TASK_TYPE! $task )

3)这种东西显然属于知识库:

   $sql
            = "UPDATE task_MY t
                INNER JOIN zz_tech_parent e
                    on t.id = e.idParent
                SET
                    t.success_count = t.success_count + 1
                WHERE
                    e.idTask =  :parTaskId";
        $params = [
            'parTaskId'      => $idTask,
        ];

类似的东西:

class GroupRepository extends NestedTreeRepository
{
    public function incrementSuccessCounterByTask(YOUR_TASK_TYPE $task){
       ....
    }
}

4)您实际上不需要在同一范围内拥有多个实体经理。因此,最好在Action的开头有一个$ em = $ this-&gt; getDoctrine() - &gt; getManager(),然后根据需要使用它。摆脱那些$ em1,$ em2等。

另外 - 这个地方 $em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );

它确实创建了一个Repository实例,而不是一个EntityManager,所以你应该将变量重命名为$taskMyRepository = ...