테스트 사이트 - 개발 중인 베타 버전입니다

그누5개발일지 REST API 에 코드 일부분에 관련된 질문입니다. 채택완료

59xk 2개월 전 조회 561

안녕하세요.

 

</p>

<p>$app->group('/v1/boards/{bo_table}', function (RouteCollectorProxy $group) {

    $group->get('', [BoardController::class, 'getBoard']);</p>

<p>    ...중략...

})

    ->add(BoardMiddleware::class)

    ->add(ConfigMiddleware::class);</p>

<p>

 

미들웨어에서

Config미들웨어에서 Config DB 접속하여 Config 없거나 에러 발생시 에러처리 되고

있으면 $request = $request->withAttribute('config', $config);

합니다

 

그리고 Config 미들웨어 실행 후 안쪽 Board미들웨어 실행 될텐데

Board 미들웨어 내용을 보면

 

</p>

<p>class BoardMiddleware

{

    private GroupService $group_service;

    private BoardService $board_service;

    private BoardPermission $board_permission;

    private BoardFileService $file_service;

    private CommentService $comment_service;

    private WriteService $write_service;</p>

<p>    public function __construct(

        GroupService $group_service,

        BoardService $board_service,

        BoardPermission $board_permission,

        BoardFileService $file_service,

        CommentService $comment_service,

        WriteService $write_service

    ) {

        $this->group_service = $group_service;

        $this->board_service = $board_service;

        $this->board_permission = $board_permission;

        $this->file_service = $file_service;

        $this->comment_service = $comment_service;

        $this->write_service = $write_service;

    }</p>

<p>    public function __invoke(Request $request, RequestHandler $handler): Response

    {

        $config = ConfigService::getConfig();</p>

<p>        // route_context 사용하여 경로 매개변수 가져오기

        $route_context = RouteContext::fromRequest($request)->getRoute();

        if ($route_context === null) {

            throw new HttpNotFoundException($request, 'url 을 찾을 수 없습니다.');

        }

        $route_arguments = $route_context->getArguments();

        $bo_table = $route_arguments['bo_table'] ?? null;

        $board = $this->board_service->getBoard($bo_table);</p>

<p>        if (!$board) {

            throw new HttpNotFoundException($request, '존재하지 않는 게시판입니다.');

        }</p>

<p>        $group = $this->group_service->fetchGroup($board['gr_id']);</p>

<p>        $request = $request->withAttribute('board', $board);

        $request = $request->withAttribute('group', $group);</p>

<p>        // 의존성 주입 클래스 설정

        $this->board_service->setBoard($board);

        $this->board_permission->setConfig($config);

        $this->board_permission->setBoard($board);

        $this->board_permission->setGroup($group);

        $this->file_service->setBoard($board);

        $this->comment_service->setBoard($board);

        $this->write_service->setBoard($board);</p>

<p>        return $handler->handle($request);

    }

}</p>

<p> </p>

<p>

 

 

    public function __invoke(Request $request, RequestHandler $handler): Response     {         $config = ConfigService::getConfig();

 

이부분에서 config 를 다시 실행 합니다 DB 조회를 두번 하게 되는 것인데

Config미들웨어에서 $request = $request->withAttribute('config', $config); 를 했으니

Board미들웨어에서 getAttribute('config') 로 써도 되는게 아닌가?

이렇게 한 이유가 있으신지 궁금합니다.

아니면 제가 잘못 알고 있는 것인지

두 미들웨어 사이에 Config 내용이 변화가 있을 수도 있기 때문인가?

정말 아무것도 몰라서 다른 이유 있는지가 궁금하여 질문 드립니다.

 

댓글을 작성하려면 로그인이 필요합니다.

답변 2개

채택된 답변
+20 포인트
웅푸
2개월 전

Slim 프레임워크에서는 ->add()로 미들웨어를 등록할 때 실행 순서는 역순이기 때문에 선생님 이 정확히 옳은생각을 하고잇는것입니다.

또한

현재 구조에서는 $request->getAttribute('config')를 사용하는 게 더 효율적라는 것이지요.

만약에

BoardMiddleware가 ConfigMiddleware보다 항상 뒤에 실행된다는 보장이 있다면, 리팩토링을 통해 중복 호출을 제거하는 게 좋을수도있습니다.

 

로그인 후 평가할 수 있습니다

댓글을 작성하려면 로그인이 필요합니다.

2개월 전
->add(ConfigMiddleware::class); 이부분이랑 ConfigMiddleware 클래스 내부에도 config가 있어서 궁금하단 말씀인가요??

 

중간에 생각되는 부분이 있어서 헷갈리네요

$request = $request->withAttribute('config', $config); 이게 어딨나요?

 

아니면 깃헙 소스코드 공유 해주세요... 

로그인 후 평가할 수 있습니다

답변에 대한 댓글 1개

5
59xk
2개월 전
https://github.com/gnuboard/gnuboard5/tree/feat/restapi/api
위가 API 부분이고

https://github.com/gnuboard/gnuboard5/blob/feat/restapi/api/v1/Routers/board.php
Board 라우터의 가장 하단에
미들 웨어가 등록 되어있습니다.
->add(BoardMiddleware::class)
->add(ConfigMiddleware::class);
ConfigMiddleware 가 먼저 실행 되고
그 후에 BoardMiddleware 가 실행 됩니다

https://github.com/gnuboard/gnuboard5/blob/feat/restapi/api/Middleware/ConfigMiddleware.php
ConfigMiddleware 내부에
$config = ConfigService::getConfig();
if (!$config) {
throw new HttpNotFoundException($request, 'Config not found.');
}

$request = $request->withAttribute('config', $config);
위 코드가 있습니다.

ConfigMiddleware실행 이후

https://github.com/gnuboard/gnuboard5/blob/feat/restapi/api/Middleware/BoardMiddleware.php
BoardMiddleware가 실행되는데
$config = ConfigService::getConfig();

다시 ConfigService::getConfig()를 하여 다시 한번 DB접속해서 config 내용을 로드 합니다.


궁금한 점은
ConfigMiddleware 에서
$request = $request->withAttribute('config', $config);
위 코드를 실행 하면

BoardMiddleware 에서
$config = $request->getAttribute('config'); 를 해도 되는 걸로 알고 있는데
다시
$config = ConfigService::getConfig(); <-- DB접속 DB에서 CONFIG 내용 저장
이렇게 하는 이유가 궁금한 점입니다
다른 의도가 있는건지 뭔지 제가 잘 몰라서 여쭤 봅니다.

댓글을 작성하려면 로그인이 필요합니다.

답변을 작성하려면 로그인이 필요합니다.

로그인