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 |
||
| 10 | class CommentsController extends Controller{ |
||
|
|
|||
| 11 | |||
| 12 | public function beforeAction(){ |
||
| 40 | |||
| 41 | /** |
||
| 42 | * get all comments |
||
| 43 | * |
||
| 44 | */ |
||
| 45 | public function getAll(){ |
||
| 59 | |||
| 60 | public function create(){ |
||
| 61 | |||
| 62 | $postId = Encryption::decryptId($this->request->data("post_id")); |
||
| 63 | |||
| 64 | $content = $this->request->data("content"); |
||
| 65 | |||
| 66 | $comment = $this->comment->create(Session::getUserId(), $postId, $content); |
||
| 67 | |||
| 68 | if(!$comment){ |
||
| 69 | $this->view->renderErrors($this->comment->errors()); |
||
| 70 | }else{ |
||
| 71 | |||
| 72 | $html = $this->view->render(Config::get('VIEWS_PATH') . 'posts/comments.php', array("comments" => $comment)); |
||
| 73 | $this->view->renderJson(array("data" => $html)); |
||
| 74 | } |
||
| 75 | } |
||
| 76 | |||
| 77 | /** |
||
| 78 | * whenever the user hits 'edit' button, |
||
| 79 | * a request will be sent to get the update form of that comment, |
||
| 80 | * so that the user can 'update' or even 'cancel' the edit request. |
||
| 81 | * |
||
| 82 | */ |
||
| 83 | View Code Duplication | public function getUpdateForm(){ |
|
| 96 | |||
| 97 | /** |
||
| 98 | * update comment |
||
| 99 | * |
||
| 100 | */ |
||
| 101 | View Code Duplication | public function update(){ |
|
| 102 | |||
| 103 | $commentId = Encryption::decryptIdWithDash($this->request->data("comment_id")); |
||
| 104 | $content = $this->request->data("content"); |
||
| 105 | |||
| 106 | if(!$this->comment->exists($commentId)){ |
||
| 107 | return $this->error(404); |
||
| 108 | } |
||
| 109 | |||
| 110 | $comment = $this->comment->update($commentId, $content); |
||
| 111 | |||
| 112 | if(!$comment){ |
||
| 113 | $this->view->renderErrors($this->comment->errors()); |
||
| 114 | }else{ |
||
| 115 | |||
| 116 | $html = $this->view->render(Config::get('VIEWS_PATH') . 'posts/comments.php', array("comments" => $comment)); |
||
| 117 | $this->view->renderJson(array("data" => $html)); |
||
| 118 | } |
||
| 119 | } |
||
| 120 | |||
| 121 | /** |
||
| 122 | * get comment by Id |
||
| 123 | * |
||
| 124 | */ |
||
| 125 | View Code Duplication | public function getById(){ |
|
| 138 | |||
| 139 | View Code Duplication | public function delete(){ |
|
| 151 | |||
| 152 | public function isAuthorized(){ |
||
| 177 | } |
||
| 178 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.