이것은 내가 Slim을 사용하는 방법입니다. 나는 경로가있는 하나의 파일을 가지고 있지만 3 계층 접근법을 사용합니다.
index.php - 여기서 어떤 논리도 처리하지 않습니다. 방금 경로를 등록하고 api 메소드 (게시, 삽입, 삭제 등)를 사용합니다.
$app->post('/bible/comment/', function() use($ioc) {
$ioc['commentApi']->post();
});
API 레이어는 슬림 앱 객체를 삽입하는 기본 클래스를 상속합니다. 거기에서 필자는 헬퍼 메소드를 사용하여 필수 필드, 선택적 필드 등을 사용하여 배열을 사용하여 요청으로부터 데이터를 추출합니다. 여기서 유효성 검사를 수행하지 않습니다. 이것은 또한 내가 xss에 대한 요청을 정리하는 곳이다.
가장 중요한 것은 여기서 예외를 처리합니다. 잘못된 요청은 예외를 throw하고 오류 응답에서 발견되어 변환됩니다.
class CommentApi extends BaseApi {
public function post() {
$fields = array(array('message', 'bookId', 'chapter', 'verseFrom', 'verseTo')):
$dtoModel = new Models\CreateComment();
$data = $this->extractFormData();
Utils::transformDto($dtoModel, $data, $fields):
try {
$result = $this->commentService->create($this->getUserId(), $dtoModel);
$response->success("You've added a book to the bible."); // helper from BaseApi to set the response 200
$response->setResult($result);
}
catch(\Exceptions\CommentRepeatedException $ex) {
$response->invalid('The foo already exist. Try a new one');
}
catch(\Exceptions\CommentsClosedException $ex) {
UtilsExceptions::invalidRequest($dtoModel, $ex);
$response->invalid('Invalid request. Check the error list for more info.');
}
$this->respond($response); // encode the response in json, set the content type, etc
}
이 계층 클래스는 리포지토리 및 기타 리소스를 사용할 비즈니스 계층을 사용합니다. 비즈니스 계층에 대해 프로젝트를 테스트하고 API 레이어는 데이터를 추출하고 dto 모델을 만들고 응답을 처리합니다.
요청/응답 모델은 상태 코드를 반환하는 인터페이스를 구현합니다. 즉, 클라이언트에서 소비 될 erros 메시지입니다 (이 점을 자동화하면 멋지다).
class CommentBusiness {
public function create($userId, Models\CreateComment $model) {
// Validate the request object
// Assert all logic requirements
$dataRes = $this->repository->create('message' => $model->getMessage(), 'bookId' => $model->getUserId(), 'chapter' => $model->getChapter(), 'verseFrom' => $mode->getVerseFrom(), 'verseTo' => $model->getVerseTo());
if($dataRes->isInvalid()) {
throw new \Exceptions\DataException($dataRes->getExModel());
}
return $dataRes;
}
}
루트 디렉토리의 모든 파일을 열 때 불필요한 파일로드 (디스크 액세스) 및 구문 분석 (CPU/메모리 사용)이 발생할 수 있으므로 앱이 너무 많이 커지는 경우이 솔루션은 성능 문제가 발생할 수 있습니다 ... – KnF