Один из разработчиков написал RESTful API для сайта, на котором редакция публикует статьи. Часть кода новой фичи разработчик передал вам на код-ревью. Сайт построен на фреймворке Yii2. Предполагается, что контроллер написан для RESTful-сервиса, а само приложение обладает (или будет впоследствии обладать) большим кол-вом бизнес-логики.
Last active
April 7, 2022 09:49
-
-
Save niksamokhvalov/69e9b2ffe1c1fe90b21429979859ef78 to your computer and use it in GitHub Desktop.
PHP RESTful API Code Review
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ArticleController | |
{ | |
protected $article_service; | |
public function __construct( | |
ArticlesService $service | |
) { | |
$this->article_service = $service; | |
} | |
public function create(Request $request) { | |
$article = $this->article_service->create($request->getBody()); | |
return $article->id; | |
} | |
public function update($id, Request $request) | |
{ | |
$this->article_service->update($request->getBody()); | |
return true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ArticlesService | |
{ | |
private $dispatcher; | |
protected $db; | |
protected $lockManager; | |
public function __construct( Dispatcher $dispatcher, DatabaseInterface $db, LockManagerInterface $lockManager ) | |
{ | |
$this->lockManager = $lockManager; | |
$this->dispatcher = $dispatcher; | |
$this->db = $db; | |
} | |
public function create($body) { | |
$article = new Article; | |
$article->load($request); | |
if (!$article->validate()) | |
{ | |
throw new BadRequestHttpException; | |
} | |
$dispatcher->trigger('article_created', $article); | |
$article->save(); | |
return $article; | |
} | |
public function update($id, $request) { | |
$this->lockManager->lock($id); | |
try { | |
$this->db->startTransaction(); | |
$article = Article::findOne($id); | |
$article->load($request); | |
$dispatcher->trigger("articleUpdate", $article); | |
$article->save(); | |
$this->db->commitTransaction(); | |
} catch (\Exception $e) { | |
$this->db->rollbackTransaction(); | |
throw $e; | |
} | |
$this->lockManager->unlock($id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment