Tick Tick Boom

시간이 다 가기 전에

개발/라라벨

laravel Request life-cycle (생명주기) dd로 따라가보기 (1)

bbingle 2023. 9. 5. 18:54

INTRO

어떤 프레임워크이던지, 처음 공부하기 시작하면 그 프레임워크의 생명주기부터 궁금해지는 것 같다.

생명주기를 알기 전까지는 마치 블랙박스 혹은 자판기 처럼 누르면(요청하면) 상품(응답)이 띡나오는 기계 같아서 조금 이해하기가 어려운 것 같다.

laravel을 사용한지 시간이 좀 지났지만, 아직까지도 생명주기를 제대로 알지 못하는 것 같아 이 기회에 처음부터 파보려고 한다. 좀 시간이 걸릴 수도 있으나, request 부터 response까지 어떻게 진행되는지 알아보자~

 

CONDITION

로컬 환경에서 진행할 생각이며, 해당 환경은 아래와 같다.

- 웹서버: valet을 이용한 로컬 호스트 (valet은 nginx 기반인 것으로 알고 있다.

- php 버전: 8.2

- laravel 버전: 10.17.1

laravel 버전은 현시점 기준 10 버전대 까지 나왔으므로 모든 탐구가 끝난 후에 10 버전대에 어떤 변경이 생기는지도 알아보겠다.

 

요청은 라라벨 기본 프로젝트 루트 페이지( 홈 화면 ) 로 접근할 때를 조건으로 살펴본다. 그럼 시작!

 

FLOW

A. public/index.php

가장 먼저, 웹서버 상의 설정으로 인해, 모든 laravel 프로젝트는 모든 로직이 public/index.php 에서 시작한다.

index.php 파일의 구성은 단촐하다.

<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/

if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

require __DIR__.'/../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
    $request = Request::capture()
)->send();

$kernel->terminate($request, $response);

 A.1. define('LARAVEL_START', microtime(true));

가장 먼저, LARAVEL_START 상수를 지정한다. 정체 불명의 상수를 지정한다.

microtime(true) 를 통해 현 시점의 타임 스탬프를 지정한다. 어디에 쓰는 상수인고 하니,,

phpstorm ai야 고맙다!

https://stackoverflow.com/questions/52882802/what-and-where-comes-the-actual-usage-of-laravel-start-const-defined-in-index-ph

 

What and Where comes the actual usage of LARAVEL_START const defined in index.php of Laravel 5.7?

When I'm looking into the Laravel Request Cycle, I encountered this line of code in the file index.php define('LARAVEL_START', microtime(true)); I didn't find any specification about this in Lar...

stackoverflow.com

라라벨의 요청 처리 시간이 얼마나 걸리는지 파악하기 원활하게 하기 위해 지정한 상수라고 한다.

프레임워크내에서 이후로 한번도 실행되지 않기 때문에, 개발자가 알아서 사용하라고 넣어둔 상수로 보인다.

 

A.2. maintenance

if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

maintenance 라는 이름에서 예측할 수 있듯이, 유지보수를 위한 라라벨 기능중 하나이다.

코드만 보면, /storage/framework 디렉토리 하위에 maintenance.php 파일이 존재할때, 해당 파일을 실행 시키는 로직이다.

아티잔 커맨드중에 down을 통해 해당 파일을 laravel 내부 stub을 통해 만들어낼 수 있고, 아티잔 커맨드 up 을 통해 해당 파일을 삭제하여 원래 상태로 만들 수 있다.

주로, 실제 운영중인 서버에서 작업을 하기 위해 사용자들의 요청을 막는 역할을 한다.

maintenaance 모드에서 접속시 503 에러가 발생한다.

https://laracasts.com/discuss/channels/laravel/laravel-maintenance-mode

 

https://laracasts.com/discuss/channels/laravel/laravel-maintenance-mode

 

laracasts.com

https://laravel.com/docs/10.x/configuration#maintenance-mode

 

Laravel - The PHP Framework For Web Artisans

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

laravel.com

 

A.3. 오토로드

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

require __DIR__.'/../vendor/autoload.php';

라라벨은 패키지 관리도구로 composer를 채택했다.

해당 로직은 composer를 통해 관리하는 패키지들을 require 하는 로직으로 laravel의 로직이라기보다는 composer를 통해 패키지를 관리하기 위한 로직에 가깝다.

composer에 대해서는 나중에 더 자세하게 알아보자.

 

A.4. 인스턴스 $app 생성하기

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

드디어, 라라벨의 대문이라고 할 수 있는 곳 앞에 바로 섰다.

주석부터 읽어보면, 


Applicaiton을 실행한다.

 

application을 가지고서부터, application의 커널을 가지고 request를 다룰 수 있다.

그러면, 우리의 application을 사용할 수 있게 response를 클라이언트의 브라우저로 되돌려보낼 수 있다. 


이 아래부터, request를 받고, response를 돌려주는 로직을 실행하는 것이다.

 

일단, 어떤 파일에서 $app 이라는 인스턴스를 가져오는 것인지 살펴보도록 하자.

 

A.4.a. bootstrap/app.php

차례인데,, 이 부분은 글이 길어지니 다음 포스트에서 살펴보도록 하자.