lundi 18 juillet 2016

Optimization - Two similar method

I'm new in Symfony and i have a little problem. I been searching online, couldn't find the answer to my problem. I create API and I have two controllers(UserController, InstructorController) with similar method (addUserImage, addInstructorImage). I created abstract BaseImage(Here is saving files), InstructorImage and UserImage(here are set path). In my controller i have:

/**
 * @ApiDoc(
 *  name="addInstructorImage", section="Instructors",
 *  description="Add Instructor Image",
 * )
 *
 * @Route("/instructor/{instructor}/image", name="instructors.image.add")
 * @Method("POST")
 *
 * @param Request    $request
 * @param Instructor $instructor
 * @View
 *
 * @return \FOS\RestBundle\View\View
 */
public function addInstructorImage(Request $request, Instructor $instructor)
{
    $this->denyAccessUnlessGranted('edit', $instructor->getUser());
    $image = new InstructorImage();
    $form = $this->get('form.factory')
            ->createNamed('', InstructorImageType::class, $image, ['csrf_protection' => false, 'method' => 'POST']);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $image->setInstructor($instructor);
        $em = $this->getDoctrine()->getManager();
        $em->persist($image);
        $em->flush();

        return $this->view(null, Response::HTTP_NO_CONTENT);
    }

    return $this->view($form, Response::HTTP_BAD_REQUEST);
}

My second controller is identical. The only difference is another object , and another form. What is the best way to optimize this code. Thank you for your help

Aucun commentaire:

Enregistrer un commentaire