찾다
백엔드 개발PHP 튜토리얼Laravel 프레임워크의 수명주기 및 원리 분석

Laravel 프레임워크의 수명주기 및 원리 분석

Jun 12, 2018 pm 04:42 PM
라라벨 프레임워크수명주기

이 글은 주로 Laravel 프레임워크의 라이프 사이클과 원리를 소개하고 있으며, 사용자 요청에 따라 Laravel 프레임워크의 전체 작동 주기, 프로세스, 원리를 예제 형식으로 요약하고 분석합니다.

이 문서의 예제는 Laravel 프레임워크의 수명을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

소개:

도구 사용 원리를 잘 알면 이 도구를 사용할 때 자신감이 생길 것입니다!

텍스트:

사용자(브라우저)가 HTTP 요청을 보내면 Apache 또는 nginx는 일반적으로 index.php로 이동하므로 후속 단계는 모두 index.php에서 시작됩니다. 먼저 이 파일의 코드를 확인하세요.

<?php
require __DIR__.&#39;/../bootstrap/autoload.php&#39;;
$app = require_once __DIR__.&#39;/../bootstrap/app.php&#39;;
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client&#39;s browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
  $request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);

저자는 댓글에서 커널의 역할에 대해 이야기했습니다. 커널은 들어오는 요청을 처리하고 해당 응답을 사용자의 브라우저로 다시 보냅니다.

여기에도 앱 개체가 포함되어 있으므로 앱 개체의 소스 코드가 첨부됩니다. 이 소스 코드는 bootstrapapp.php

<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
  realpath(__DIR__.&#39;/../&#39;)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
  Illuminate\Contracts\Http\Kernel::class,
  App\Http\Kernel::class
);
$app->singleton(
  Illuminate\Contracts\Console\Kernel::class,
  App\Console\Kernel::class
);
$app->singleton(
  Illuminate\Contracts\Debug\ExceptionHandler::class,
  App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

앱 변수임을 확인하시기 바랍니다. IlluminateFoundationApplication 클래스 개체에 속하므로 이 클래스의 생성자가 정확히 무엇을 하는지 소스 코드를 살펴보겠습니다.

public function __construct($basePath = null)
{
  if ($basePath) {
    $this->setBasePath($basePath);
  }
  $this->registerBaseBindings();
  $this->registerBaseServiceProviders();
  $this->registerCoreContainerAliases();
}

생성자는 3가지 작업을 수행합니다. 처음 두 가지는 컨테이너 생성, ServiceProvider 등록, 코드 살펴보기

/**
 * Register the basic bindings into the container.
 *
 * @return void
 */
protected function registerBaseBindings()
{
  static::setInstance($this);
  $this->instance(&#39;app&#39;, $this);
  $this->instance(Container::class, $this);
}
/**
 * Register all of the base service providers.
 *
 * @return void
 */
protected function registerBaseServiceProviders()
{
  $this->register(new EventServiceProvider($this));
  $this->register(new LogServiceProvider($this));
  $this->register(new RoutingServiceProvider($this));
}

마지막 작업입니다. 배열은 프로그래머가 똑똑하고 게으르다는 것을 보여주는 많은 수의 별칭을 정의합니다.

/**
 * Register the core class aliases in the container.
 *
 * @return void
 */
public function registerCoreContainerAliases()
{
  $aliases = [
    &#39;app&#39;         => [\Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class],
    &#39;auth&#39;         => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],
    &#39;auth.driver&#39;     => [\Illuminate\Contracts\Auth\Guard::class],
    &#39;blade.compiler&#39;    => [\Illuminate\View\Compilers\BladeCompiler::class],
    &#39;cache&#39;        => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class],
    &#39;cache.store&#39;     => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::class],
    &#39;config&#39;        => [\Illuminate\Config\Repository::class, \Illuminate\Contracts\Config\Repository::class],
    &#39;cookie&#39;        => [\Illuminate\Cookie\CookieJar::class, \Illuminate\Contracts\Cookie\Factory::class, \Illuminate\Contracts\Cookie\QueueingFactory::class],
    &#39;encrypter&#39;      => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class],
    &#39;db&#39;          => [\Illuminate\Database\DatabaseManager::class],
    &#39;db.connection&#39;    => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class],
    &#39;events&#39;        => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class],
    &#39;files&#39;        => [\Illuminate\Filesystem\Filesystem::class],
    &#39;filesystem&#39;      => [\Illuminate\Filesystem\FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class],
    &#39;filesystem.disk&#39;   => [\Illuminate\Contracts\Filesystem\Filesystem::class],
    &#39;filesystem.cloud&#39;   => [\Illuminate\Contracts\Filesystem\Cloud::class],
    &#39;hash&#39;         => [\Illuminate\Contracts\Hashing\Hasher::class],
    &#39;translator&#39;      => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class],
    &#39;log&#39;         => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::class, \Psr\Log\LoggerInterface::class],
    &#39;mailer&#39;        => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\Mail\Mailer::class, \Illuminate\Contracts\Mail\MailQueue::class],
    &#39;auth.password&#39;    => [\Illuminate\Auth\Passwords\PasswordBrokerManager::class, \Illuminate\Contracts\Auth\PasswordBrokerFactory::class],
    &#39;auth.password.broker&#39; => [\Illuminate\Auth\Passwords\PasswordBroker::class, \Illuminate\Contracts\Auth\PasswordBroker::class],
    &#39;queue&#39;        => [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class],
    &#39;queue.connection&#39;   => [\Illuminate\Contracts\Queue\Queue::class],
    &#39;queue.failer&#39;     => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],
    &#39;redirect&#39;       => [\Illuminate\Routing\Redirector::class],
    &#39;redis&#39;        => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class],
    &#39;request&#39;       => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class],
    &#39;router&#39;        => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class],
    &#39;session&#39;       => [\Illuminate\Session\SessionManager::class],
    &#39;session.store&#39;    => [\Illuminate\Session\Store::class, \Illuminate\Contracts\Session\Session::class],
    &#39;url&#39;         => [\Illuminate\Routing\UrlGenerator::class, \Illuminate\Contracts\Routing\UrlGenerator::class],
    &#39;validator&#39;      => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class],
    &#39;view&#39;         => [\Illuminate\View\Factory::class, \Illuminate\Contracts\View\Factory::class],
  ];
  foreach ($aliases as $key => $aliases) {
    foreach ($aliases as $alias) {
      $this->alias($key, $alias);
    }
  }
}

여기에 인스턴스 함수가 ​​나타납니다. 사실 이는 Application 클래스의 함수가 아니라 Application 클래스의 상위 클래스인 Container 클래스의 함수입니다.

/**
 * Register an existing instance as shared in the container.
 *
 * @param string $abstract
 * @param mixed  $instance
 * @return void
 */
public function instance($abstract, $instance)
{
  $this->removeAbstractAlias($abstract);
  unset($this->aliases[$abstract]);
  // We&#39;ll check to determine if this type has been bound before, and if it has
  // we will fire the rebound callbacks registered with the container and it
  // can be updated with consuming classes that have gotten resolved here.
  $this->instances[$abstract] = $instance;
  if ($this->bound($abstract)) {
    $this->rebound($abstract);
  }
}

Application은 Container의 하위 클래스이므로 $app는 Application 클래스의 객체일 뿐만 아니라 Container의 객체이기도 합니다. 따라서 의 소스 코드 파일에서 새로운 $app不仅是Application类的对象,还是Container的对象,所以,新出现的singleton函数我们就可以到Container类的源代码文件里查。bind函数和singleton的区别见这篇博文。

singleton这个函数,前一个参数是实际类名,后一个参数是类的“别名”。

$appsingleton 함수를 확인할 수 있습니다. 컨테이너 클래스. 바인드 함수와 싱글톤의 차이점은 이 블로그 게시물에서 확인할 수 있습니다. singleton 이 함수의 첫 번째 매개변수는 실제 클래스 이름이고, 뒤의 매개변수는 클래스의 "별칭"입니다. $app 객체는 3개의 싱글톤 모델 객체, 즉 HttpKernel

,

ConsoleKernel

,

ExceptionHandler을 선언합니다. 여기서는 객체가 생성되지 않으며 단지 선언과 "별칭"

일 뿐이라는 점에 유의하세요.

index.php에도 $kernel 변수가 있지만 make의 HttpKernel 변수만 저장되므로 이 기사에서는 ConsoleKernel 및 ExceptionHandler에 대해 논의하지 않습니다. . .

계속해서 폴더에서

AppHttpKernel.php

를 찾으세요. HttpKernel이 수행하는 모든 실제 작업을 이 PHP 파일에 작성했으므로 이 코드에서 정확히 수행되는 작업을 살펴보겠습니다.

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
  /**
   * The application&#39;s global HTTP middleware stack.
   *
   * These middleware are run during every request to your application.
   *
   * @var array
   */
  protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    //\App\Http\Middleware\MyMiddleware::class,
  ];
  /**
   * The application&#39;s route middleware groups.
   *
   * @var array
   */
  protected $middlewareGroups = [
    &#39;web&#39; => [
      \App\Http\Middleware\EncryptCookies::class,
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
      \Illuminate\Session\Middleware\StartSession::class,
      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      \App\Http\Middleware\VerifyCsrfToken::class,
    ],
    &#39;api&#39; => [
      &#39;throttle:60,1&#39;,
    ],
  ];
  /**
   * The application&#39;s route middleware.
   *
   * These middleware may be assigned to groups or used inpidually.
   *
   * @var array
   */
  protected $routeMiddleware = [
    &#39;auth&#39; => \App\Http\Middleware\Authenticate::class,
    &#39;auth.basic&#39; => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    &#39;guest&#39; => \App\Http\Middleware\RedirectIfAuthenticated::class,
    &#39;throttle&#39; => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  &#39;mymiddleware&#39;=>\App\Http\Middleware\MyMiddleware::class,
  ];
}

미들웨어 배열이 HttpKernel에 정의되어 있다는 것을 한눈에 알 수 있습니다.

해야 할 일이 끝나면 요청부터 응답까지의 프로세스가 시작됩니다. index.php

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

를 참조하세요. 마지막으로 모든 리소스를 종료하고 해제합니다.

/**
* Call the terminate method on any terminable middleware.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response $response
* @return void
*/
public function terminate($request, $response)
{
    $this->terminateMiddleware($request, $response);
    $this->app->terminate();
}

전체 프로세스를 간단히 요약하면 다음과 같습니다.

1.index.php는 bootstrapapp.php을 로드하고, Application 클래스의 생성자에 컨테이너를 생성하고, ServiceProvider를 등록합니다. 별칭 array 를 정의한 다음 app 변수를 사용하여 생성자가 생성한 객체를 저장합니다. 2. 앱 개체를 사용하여 싱글톤 모드 개체 HttpKernel을 만듭니다. HttpKernel을 만들 때 생성자가 호출되어 미들웨어 선언을 완료합니다. 3. 방문을 요청하기 전에 위 작업이 완료됩니다. 그런 다음 요청을 기다린 후 요청 수락

-->

요청 처리

-->

응답 보내기

--> ;

앱 변수 중지

위 내용은 모두의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용을 보려면 PHP 중국어 웹사이트를 주목하세요.

관련 권장 사항:
Laravel 프레임워크는 미들웨어를 사용하여 작업 로깅 기능을 구현합니다.

Laravel 프레임워크는 리스너를 사용하여 SQL 문 기록 기능을 구현합니다.

Laravel 프레임워크 라우팅 설정

🎜🎜🎜 🎜🎜🎜🎜

위 내용은 Laravel 프레임워크의 수명주기 및 원리 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
과대 광고 : 오늘 PHP의 역할을 평가합니다과대 광고 : 오늘 PHP의 역할을 평가합니다Apr 12, 2025 am 12:17 AM

PHP는 현대적인 프로그래밍, 특히 웹 개발 분야에서 강력하고 널리 사용되는 도구로 남아 있습니다. 1) PHP는 사용하기 쉽고 데이터베이스와 완벽하게 통합되며 많은 개발자에게 가장 먼저 선택됩니다. 2) 동적 컨텐츠 생성 및 객체 지향 프로그래밍을 지원하여 웹 사이트를 신속하게 작성하고 유지 관리하는 데 적합합니다. 3) 데이터베이스 쿼리를 캐싱하고 최적화함으로써 PHP의 성능을 향상시킬 수 있으며, 광범위한 커뮤니티와 풍부한 생태계는 오늘날의 기술 스택에 여전히 중요합니다.

PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?Apr 12, 2025 am 12:13 AM

PHP에서는 약한 참조가 약한 회의 클래스를 통해 구현되며 쓰레기 수집가가 물체를 되 찾는 것을 방해하지 않습니다. 약한 참조는 캐싱 시스템 및 이벤트 리스너와 같은 시나리오에 적합합니다. 물체의 생존을 보장 할 수 없으며 쓰레기 수집이 지연 될 수 있음에 주목해야합니다.

PHP의 __invoke 마법 방법을 설명하십시오.PHP의 __invoke 마법 방법을 설명하십시오.Apr 12, 2025 am 12:07 AM

\ _ \ _ 호출 메소드를 사용하면 객체를 함수처럼 호출 할 수 있습니다. 1. 객체를 호출 할 수 있도록 메소드를 호출하는 \ _ \ _ 정의하십시오. 2. $ obj (...) 구문을 사용할 때 PHP는 \ _ \ _ invoke 메소드를 실행합니다. 3. 로깅 및 계산기, 코드 유연성 및 가독성 향상과 같은 시나리오에 적합합니다.

동시성에 대해 PHP 8.1의 섬유를 설명하십시오.동시성에 대해 PHP 8.1의 섬유를 설명하십시오.Apr 12, 2025 am 12:05 AM

섬유는 PHP8.1에 도입되어 동시 처리 기능을 향상시켰다. 1) 섬유는 코 루틴과 유사한 가벼운 동시성 모델입니다. 2) 개발자는 작업의 실행 흐름을 수동으로 제어 할 수 있으며 I/O 집약적 작업을 처리하는 데 적합합니다. 3) 섬유를 사용하면보다 효율적이고 반응이 좋은 코드를 작성할 수 있습니다.

PHP 커뮤니티 : 자원, 지원 및 개발PHP 커뮤니티 : 자원, 지원 및 개발Apr 12, 2025 am 12:04 AM

PHP 커뮤니티는 개발자 성장을 돕기 위해 풍부한 자원과 지원을 제공합니다. 1) 자료에는 공식 문서, 튜토리얼, 블로그 및 Laravel 및 Symfony와 같은 오픈 소스 프로젝트가 포함됩니다. 2) 지원은 StackoverFlow, Reddit 및 Slack 채널을 통해 얻을 수 있습니다. 3) RFC에 따라 개발 동향을 배울 수 있습니다. 4) 적극적인 참여, 코드에 대한 기여 및 학습 공유를 통해 커뮤니티에 통합 될 수 있습니다.

PHP vs. Python : 차이점 이해PHP vs. Python : 차이점 이해Apr 11, 2025 am 12:15 AM

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP : 죽어 가거나 단순히 적응하고 있습니까?PHP : 죽어 가거나 단순히 적응하고 있습니까?Apr 11, 2025 am 12:13 AM

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래 : 적응 및 혁신PHP의 미래 : 적응 및 혁신Apr 11, 2025 am 12:01 AM

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전