> For the complete documentation index, see [llms.txt](https://tobyisme.gitbook.io/laravel/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tobyisme.gitbook.io/laravel/cheng-xu-you-hua-ji-qiao.md).

# 程序優化技巧

### *性能一直是Laravel 框架為人詬病的一個點，所以調優Laravel 程序算是一個必學的技能。*

## 配置信息緩存 artisan config:cache

使用以下Artisan自帶命令，把`config`文件夾裡所有配置信息合併到一個文件裡，減少運行時文件的載入數量：

```
php artisan config:cache
```

上面命令會生成文件`bootstrap/cache/config.php`，可以使用以下命令來取消配置信息緩存：

```
php artisan config:clear
```

此命令做的事情就是把`bootstrap/cache/config.php`文件刪除。

> 注意：配置信息緩存不會隨著更新而自動重載，所以，開發時候建議關閉配置信息緩存，一般在生產環境中使用，可以配合[Envoy任務運行器](https://doc.laravel-china.org/docs/5.1/envoy)一起使用。

## 路由緩存 artisan route:cache

路由緩存可以有效的提高路由器的註冊效率，在大型應用程序中效果越加明顯，可以使用以下命令：

```
php artisan route:cache
```

以上命令會生成`bootstrap/cache/routes.php`文件，需要注意的是，路由緩存不支持路由匿名函數編寫邏輯，詳見：[文檔-路由緩存](https://doc.laravel-china.org/docs/5.1/controllers#路由缓存)。

可以使用下面命令清除路由緩存：

```
php artisan route:clear
```

此命令做的事情就是把`bootstrap/cache/routes.php`文件刪除。

> 注意：路由緩存不會隨著更新而自動重載，所以，開發時候建議關閉路由緩存，一般在生產環境中使用，可以配合[Envoy任務運行器](https://doc.laravel-china.org/docs/5.1/envoy)一起使用。

## 類映射加載優化 artisan optimize

`optimize`命令把常用加載的類合併到一個文件裡，通過減少文件的加載，來提高運行效率：

```
php artisan optimize --force
```

會生成`bootstrap/cache/compiled.php`和`bootstrap/cache/services.json`兩個文件。

你可以可以通過修改`config/compile.php`文件來添加要合併的類。

在`production`環境中，參數`--force`不需要指定，文件就會自動生成。

要清除類映射加載優化，請運行以下命令：

```
php artisan clear-compiled
```

此命令會刪除上面`optimize`生成的兩個文件。

> 注意：此命令要運行在`php artisan config:cache`後，因為`optimize`命令是根據配置信息（如：`config/app.php`文件的`providers`數組）來生成文件的。

## 自動加載優化 composer dumpautoload

此命令不止針對於Laravel程序，適用於所有使用`composer`來構建的程序。此命令會把`PSR-0`和`PSR-4`轉換為一個類映射表，來提高類的加載速度。

```
composer dumpautoload -o
```

> 注意：`php artisan optimize --force`命令裡已經做了這個操作。

## 使用Memcached 來存儲會話 config/session.php

每一個Laravel的請求，都會產生會話，修改會話的存儲方式能有效提高程序效率，會話的配置信息是`config/session.php`，建議修改為Memcached或者Redis等專業的緩存軟件：

```
'driver' => 'memcached',
```

## 使用專業緩存驅動器 config/cache.php

「緩存」是提高應用程序運行效率的法寶之一，默認緩存驅動是`file`文件緩存，建議切換到專業的緩存系統，如Redis或者Memcached，不建議使用數據庫緩存。

```
'default' => 'redis',
```

## 數據庫請求優化

數據庫請求優化

* 數據關聯模型讀取時使用[延遲預加載](https://doc.laravel-china.org/docs/5.1/eloquent-relationships#%E9%A2%84%E5%8A%A0%E8%BD%BD)和[預加載](https://doc.laravel-china.org/docs/5.1/eloquent-relationships#%E9%A2%84%E5%8A%A0%E8%BD%BD)；
* 使用[Laravel Debugbar](https://github.com/barryvdh/laravel-debugbar)或者[Clockwork](https://laravel-china.org/topics/23)留意每一個頁面的總數據庫請求數量；

這裡的篇幅只寫到與Laravel 相關的，其他關於數據優化的內容，請自行查閱其他資料。

## 為數據集書寫緩存邏輯

合理的使用Laravel 提供的緩存層操作，把從數據庫裡面拿出來的數據集合進行緩存，減少數據庫的壓力，運行在內存上的專業緩存軟件對數據的讀取也遠遠快於數據庫。

```
$posts = Cache::remember('index.posts', $minutes = 30, function()

{

    return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();

});
```

`remember`甚至連數據關聯模型也都一併緩存了，多麼方便呀。

## 使用即時編譯器（JIT），如：HHVM、OpCache

HHVM和OpCache都能輕輕鬆鬆的讓你的應用程序在不用做任何修改的情況下，直接提高50%或者更高的性能，PHPhub之前做個一個實驗，具體請見：[使用OpCache提升PHP 5.5+程序性能](https://laravel-china.org/topics/301)。

## 前端資源合併Elixir

作為優化的標準，一個頁面只應該加載一個CSS 和一個JS 文件，並且文件要能方便走CDN，需要文件名隨著修改而變化。

Laravel Elixir提供了一套簡便實用的方案，詳細請見文檔：[Laravel Elixir文檔](https://doc.laravel-china.org/docs/5.1/elixir)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://tobyisme.gitbook.io/laravel/cheng-xu-you-hua-ji-qiao.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
