\$\begingroup\$
\$\endgroup\$
1
I have a function which does the following:
- When new Post Entity is added some fields in Category table are updated.
- When new Thread Entity is added the same fields in Category table are updated.
Because of this, some lines are completely the same.
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();
$entityManager = $args->getObjectManager();
if ($entity instanceof Post) {
$post = $entity;
$thread = $post->getThread();
$category = $thread->getCategory();
$category->setLastPostThreadTitle($thread->getTitle());
$category->setLastPostThreadSlug($thread->getSlug());
$category->setLastPostBody($post->getBody());
$category->setLastPosterUsername($post->getUser()->getUsername());
$category->setLastPostCreatedAt($post->getCreatedAt());
$category->setIsLastPostOp(false);
$category->setPosts($category->getPosts() + 1);
$entityManager->merge($category);
$entityManager->flush();
}
if ($entity instanceof Thread) {
$thread = $entity;
$category = $thread->getCategory();
$category->setLastPostThreadTitle($thread->getTitle());
$category->setLastPostThreadSlug($thread->getSlug());
$category->setLastPostBody($thread->getBody());
$category->setLastPosterUsername($thread->getUser()->getUsername());
$category->setLastPostCreatedAt($thread->getCreatedAt());
$category->setIsLastPostOp(true);
$entityManager->merge($category);
$entityManager->flush();
}
}
How would be possible to refactor this code to avoid WET?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 25, 2019 at 13:33
user191251user191251
-
\$\begingroup\$ Errr.... Move the common code above if? \$\endgroup\$Your Common Sense– Your Common Sense2019年01月25日 13:41:34 +00:00Commented Jan 25, 2019 at 13:41
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
How about something like this there is some checking that needs to be done because I inverse the $isPost
bool and that could be buggy
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();
$entityManager = $args->getObjectManager();
$isPost = $entity instanceof Post;
$thread = $isPost ? $post->getThread() : $entity;
$details = $isPost ? $entity : $thread;
$category = $thread->getCategory();
$category->setLastPostThreadTitle($thread->getTitle());
$category->setLastPostThreadSlug($thread->getSlug());
$category->setLastPostBody($details->getBody());
$category->setLastPosterUsername($details->getUser()->getUsername());
$category->setLastPostCreatedAt($details->getCreatedAt());
//NOTE the inversion of the isPost bool
//TODO Test this
$category->setIsLastPostOp(!$isPost);
if($isPost){
$category->setPosts($category->getPosts() + 1);
}
$entityManager->merge($category);
$entityManager->flush();
}
-
\$\begingroup\$ It works:). Just had to change $post->getThread() to $entity->getThread(), because $post is undefined on line 8 \$\endgroup\$user191251– user1912512019年01月25日 14:31:00 +00:00Commented Jan 25, 2019 at 14:31
lang-php