Table of Contents
Laravel directory structure and configuration
Directory structure
Configuration file
总结
Home PHP Framework Laravel Complete Laravel directory structure and configuration in half an hour

Complete Laravel directory structure and configuration in half an hour

Feb 15, 2022 pm 05:33 PM
laravel

This article brings you knowledge about Laravel directory structure and configuration. Laravel's directory structure is relatively richer in the initial state. In addition to the traditional controller, it also helps us prepare The directory of code files such as scripts and middleware can basically be used directly. I hope it will be helpful to everyone.

Complete Laravel directory structure and configuration in half an hour

Laravel directory structure and configuration

Laravel’s directory structure will be relatively richer in the initial state. In addition to the traditional controller, It also helps us prepare directories for code files such as scripts and middleware, which can basically be used directly.

Directory structure

First let’s take a look at what’s in the root directory.

Complete Laravel directory structure and configuration in half an hour

In fact, you can know the functions of these directories based on their names. For example, the app directory is the specific application code. The config directory stores configuration file information. In the previous article, we mentioned that if you use Laravel in a virtual machine, you need to use the file server.php in the root directory. In fact, this file loads public/index.php in the root directory. document.

bootstrap is a file that needs to be loaded when starting the framework. Generally, the contents of this file are not modified. This directory also contains cache-related directory files. database is obviously database related content. public is the entry directory of our framework. Other resource files can also be placed here, such as directly displayed images and static files. resources stores views and uncompiled resource files.

routes directory is the directory where routing files are stored. This directory is very important. Of course, it is actually the routing files inside that are very important. It contains web.php, api.php, channels.php and console.php by default, which respectively represent the default web request routing, api request routing, registration event broadcast and closure-based console script commands.

The storage directory is used to store various files generated by the application, including cache, logs and other information. The tests directory contains content related to automated testing.

In these directories, let’s focus on the content contained in the app directory.

Complete Laravel directory structure and configuration in half an hour

The app directory is the most commonly used directory in our application development. The controllers, models, middleware and other content of our application are all in this directory.

The Console directory is the command line script directory we wrote, that is, the command line functions that can be customized and run through php artisan are all in this directory.

Exceptions are exception classes that we can customize. Models store our customized data models. The Providers directory stores default and some service providers that we can customize.

Next is the Http directory.

Controllers Needless to say, the controllers are all written here. Middleware contains the default middleware. Of course, our customized middleware can also be written in this directory.

Kernel.php is the control file for requesting the kernel. In this file, we can define the requested middleware. This is also a very important core document. We will explain it in detail when we learn it in the future.

Configuration file

The content about the directory structure is actually the above. Next, let’s take a look at the configuration file, which is the content in the config directory under the root directory. The content here is also what we often Need to be exposed.

Complete Laravel directory structure and configuration in half an hour

In fact, you can see their functions from the names of these configuration files. In the next article, we will soon come into contact with the database.php file, because in the entry-related content, we still need to simply connect to the database to experience it.

In database.php, you can not only define the mysql database information to be connected, but also the NoSQL type database to be connected (redis connection configuration has been given by default). Let’s take a look at the MySQL connection information here.

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],
Copy after login

Through the configuration file code, we can see that a lot of information is obtained through the env() function. The content obtained by this function is actually the content of the .env file in the root directory. Opening this .env file, we can see that the configuration method is similar to that of the php.ini file, and both have configuration information in the form of key=value.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Copy after login

Here, we can configure the database connection information in the current environment. What are the benefits of this configuration?

独立的配置文件这种形式的很容易实现配置中心,也很容易实现测试环境和正式环境的分别部署。一般我们不会将这个 .env 放到 git 中,或者跟随代码上传。在正式环境或者测试环境都是手动地或者通过配置中心来进行配置。这样的话,我们就不需要修改源代码,只需要使用不同的这个 .env 配置文件就可以实现不同的环境下运行相同的代码了。

通过 XDebug ,我们可以追踪到 env() 这个方法在底层调用了 vlucas 的 DotEnv 这个 Composer 组件来进行 PHPENV 类型文件的读写加载。

对于加载来说,在程序运行的时候,我们会通过下面这段代码来进行加载。

// laravel/framework/src/Illuminate/Foundation/Application.php
foreach ($bootstrappers as $bootstrapper) {
    $this['events']->dispatch('bootstrapping: '.$bootstrapper, [$this]);

    $this->make($bootstrapper)->bootstrap($this);

    $this['events']->dispatch('bootstrapped: '.$bootstrapper, [$this]);
}
Copy after login

其中核心是 $this->make($bootstrapper)->bootstrap($this); 这一段,它在循环中会加载所有 $bootstrappers 数组中的内容,这个数组里面的内容是在 laravel/framework/src/Illuminate/Foundation/Http/Kernel.php 中的类变量 $bootstrappers 所定义的。第一个环境变量启动加载器就是我们加载配置文件所需要的,如下所示:

// laravel/framework/src/Illuminate/Foundation/Http/Kernel.php
/**
 * The bootstrap classes for the application.
 *
 * @var string[]
 */
protected $bootstrappers = [
    \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
    \Illuminate\Foundation\Bootstrap\LoadConfiguration::class,
    \Illuminate\Foundation\Bootstrap\HandleExceptions::class,
    \Illuminate\Foundation\Bootstrap\RegisterFacades::class,
    \Illuminate\Foundation\Bootstrap\RegisterProviders::class,
    \Illuminate\Foundation\Bootstrap\BootProviders::class,
];
Copy after login

源码中和代码中的 Bootstrap 相关的内容都是启动加载器的实现,从文件名就可以看出,这个启动加载器是加载环境变量相关内容的。.env 文件里面的配置信息也将是以整体的环境变量的形式加载到系统中。

// laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php
$this->createDotenv($app)->safeLoad();
Copy after login

LoadEnvironmentVariables.php 中会通过上述代码进入到 DotEnv 组件中,通过以下方法读取配置文件相关的信息。

// vlucas/phpdotenv/src/Dotenv.php
create() 

// vlucas/phpdotenv/src/Loader/Loader.php 
load()
Copy after login

最后通过 ServerConstAdapter.php 文件中的 write() 方法将这些配置文件中的信息写入到 $_SERVER 全局变量数组中。

//vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php 
/**
 * Write to an environment variable, if possible.
 *
 * @param string $name
 * @param string $value
 *
 * @return bool
 */
public function write(string $name, string $value)
{
    $_SERVER[$name] = $value;

    return true;
}
Copy after login

在路由文件中,我们可以通过打印 \$_SERVER 数据看到配置文件里面我们配置过的信息。之后的读取,也直接是读取这个 $_SERVER 中的数据。

Route::get('/', function () {
    var_dump($_SERVER);

    var_dump(env('REDIS_PASSWORD')); // null
    $_SERVER['REDIS_PASSWORD'] = '123456';
    var_dump(env('REDIS_PASSWORD')); // string '123456'
    
    return view('welcome');
});
Copy after login

其实反过来看,我们的 Laravel 就是将 .env 文件中的数据缓存到了全局变量 $_SERVER ,然后我们在将来使用的时候就直接从全局变量中获取就可以了,这样就可以避免下一次还要从文件读取,从而提高系统效率。

总结

一开始以为就是简单地讲讲目录和配置文件,没想到吧,直接就进入源码的分析了。当然,这只是开胃菜而已。对于框架架构的学习,一定要配置好 XDebug 之类的调试工具,如果没这些工具,这种使用了许多 Composer 组件来回调用的代码还真不好找出最终实现的地方。

后面的文章也都会以这样的方式进行,需要注意的是,我们的源码都是在 vendor 目录下的,所以有的文章中这个路径我就没有写了。

【相关推荐:laravel视频教程

The above is the detailed content of Complete Laravel directory structure and configuration in half an hour. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles