Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 17 | class CommentController implements InjectionAwareInterface |
||
| 18 | { |
||
| 19 | use InjectionAwareTrait; |
||
| 20 | |||
| 21 | public function deleteComment($commentId) |
||
| 30 | |||
| 31 | public function editComment($commentid) |
||
| 48 | |||
| 49 | 1 | View Code Duplication | public function viewAllPosts() |
| 50 | { |
||
| 51 | 1 | $title = "Retrieve all posts"; |
|
| 52 | 1 | $view = $this->di->get("view"); |
|
| 53 | 1 | $pageRender = $this->di->get("pageRender"); |
|
| 54 | 1 | $post = new Post(); |
|
| 55 | 1 | $post->setDb($this->di->get("db")); |
|
| 56 | |||
| 57 | $data = [ |
||
| 58 | 1 | "items" => $post->findAll(), |
|
| 59 | 1 | ]; |
|
| 60 | |||
| 61 | 1 | $view->add("comment/viewAllPosts", $data); |
|
| 62 | |||
| 63 | 1 | return $pageRender->renderPage(["title" => $title]); |
|
| 64 | } |
||
| 65 | |||
| 66 | View Code Duplication | public function newPost() |
|
| 83 | |||
| 84 | 1 | View Code Duplication | public function newComment($id) |
| 85 | { |
||
| 86 | if ($this->di->get("session")->has("email")) { |
||
| 87 | $title = "Create new comment"; |
||
| 88 | $view = $this->di->get("view"); |
||
| 89 | $pageRender = $this->di->get("pageRender"); |
||
| 90 | $form = new CreateCommentForm($this->di, $id); |
||
| 91 | |||
| 92 | $form->check(); |
||
| 93 | |||
| 94 | $data = [ |
||
| 95 | "form" => $form->getHTML(), |
||
| 96 | ]; |
||
| 97 | |||
| 98 | $view->add("comment/addNewComment", $data); |
||
| 99 | |||
| 100 | $pageRender->renderPage(["title" => $title]); |
||
| 101 | } else { |
||
| 102 | $login = $this->di->get("url")->create("user/login"); |
||
| 103 | $this->di->get("response")->redirect($login); |
||
| 104 | return false; |
||
| 105 | } |
||
| 106 | 1 | } |
|
| 107 | |||
| 108 | public function postAndComments($id) |
||
| 140 | } |
||
| 141 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: