I am adding some code to a php class which has several functions with repeated code that I'd like to refactor. The functions look like the following:
public function similarName($arg1, $arg2, $differentObject) { // $arg1 and $arg2 are common to all functions if ($firstCheck) { // some code if($secondCheck) { // some code if ($thirdCheck) { // unique code with $differentObject } } } // return statement } I need to add now a new function following exactly the same, but the unique code.
The following are the things that came to my mind:
- Use a callback function as a parameter, not sure how to.
- Use a single function with the common code, and return a boolean value. If true then execute unique code in every single function. This seems inelegant to me.
- Using an abstract class and a template abstract method for the unique code, but I am not sure how to pass the $differentObject.
- I am even wondering if this is a Decorator pattern issue, but I never used it this way.
What is the right pattern for this?
UPDATE:
The following are two of those functions with the real code. They are Symfony2 form handlers which add uploaded image for the object
public function handleToPost(FormInterface $form, Request $request, Post $post) { if ($request->getMethod() == 'POST') { $form->bind($request); $data = $form->getData(); $file = $data['file']; if($data['file']) { $imageConstraint = new \Symfony\Component\Validator\Constraints\Image(); $imageConstraint->maxSizeMessage = Image::ERROR_MESSAGE; $imageConstraint->maxSize = Image::MAX_SIZE; $errorList = $this->validator->validateValue($file, $imageConstraint); if (count($errorList) == 0) { if (!$post->getImage()) { $image = new ImagePost(); $image->setPost($post); $image->setFile($file); $this->imageManager->saveImage($image); } else { $image = $post->getImage(); $image->setFile($file); } $this->imageManager->createImage($image); } else { return false; } return true; } } return false; } public function handleToEvent(FormInterface $form, Request $request, Event $event) { if ($request->getMethod() == 'POST') { $form->bind($request); $data = $form->getData(); $file = $data['file']; if ($data['file']) { $imageConstraint = new \Symfony\Component\Validator\Constraints\Image(); $imageConstraint->maxSizeMessage = Image::ERROR_MESSAGE; $imageConstraint->maxSize = Image::MAX_SIZE; $errorList = $this->validator->validateValue($file, $imageConstraint); if (count($errorList) == 0) { if (!$event->getImage()) { $image = new ImageEvent(); $image->setEvent($event); $image->setFile($file); $this->imageManager->saveImage($image); } else { $image = $event->getImage(); $image->setFile($file); } $this->imageManager->createImage($image); } else { return false; } return true; } else { return true; } } return false; }