PHP最大化 Laravel 性能:Web 开发人员的基本优化策略

简介

就网站而言,应用程序/网站的性能会影响用户体验和搜索引擎排名。使用 PHP 框架 Laravel 进行开发时,您可以获得该框架中包含的功能和技术,以优化您的网站的速度和效率。在这篇文章中,我们将讨论 Laravel 的优化,使用有效的缓存策略、高效的数据库查询、延迟加载与急切加载以及其他一些技术来提高性能。

缓存策略

缓存用于减少数据库的负载并加快响应速度。Laravel 有许多缓存后端,例如 Memcached 和 Redis。这些在 Laravel 中实现起来非常简单。

// Cache a query result for 60 minutes
$posts = Cache::remember('posts', 60, function () {
    return Post::all();
});

此代码检查是否存在posts,如果没有则获取它们并将它们添加到缓存中 60 分钟。

use Illuminate\Support\Facades\Cache;

$popularPosts = Cache::remember('popular_posts', 1440, function () {
    return Post::with('author', 'comments')
               ->where('views', '>', 1000)
               ->orderBy('views', 'DESC')
               ->take(10)
               ->get();
});

此查询将排名前 10 的热门帖子及其相关作者和评论缓存 1440 分钟(24 小时)。此查询用于with最小化执行的查询数量。

Laravel 优化的数据库查询编写

我们总是尝试改进我们的数据库查询,但 Laravel 提供了 Eloquent ORM,可以轻松地以简单的方式编写复杂的查询,但最重要的是知道如何编写有效的查询。

// Instead of fetching all columns, specify only the needed ones
$users = User::select('id', 'name', 'email')->get();

该查询小而具体,减少了数据库不必要的负载。它只获取需要的东西。

$postsWithActiveAuthors = Post::whereHas('author', function ($query) {
    $query->where('active', 1);
})->get();

此代码片段使用whereHas方法来获取具有活跃作者的帖子(非常有用)。它通过避免加载所有帖子来提高查询效率。

延迟加载与预加载

Laravel 为您提供了如何加载相关模型的选项。Lazily 表示相关模型按需加载,Eagerly 表示一次性加载相关模型。大多数情况下,预加载是首选方式,除非您有非常特殊的延迟加载情况。

// Lazy loading (inefficient)
$books = Book::all();
foreach ($books as $book) {
    echo $book->author->name;
}

// Eager loading (efficient)
$books = Book::with('author')->get();
foreach ($books as $book) {
    echo $book->author->name;
}

预加载在单个查询中获取相关模型,避免了延迟加载的 N+1 问题。

效率低下:这里每个用户的帖子都不会被获取,直到它们在循环内被访问,从而导致多个查询。

$users = User::all();
foreach ($users as $user) {
    // This will execute a new query for each user to get their posts
    foreach ($user->posts as $post) {
        echo $post->title;
    }
}

高效: with('posts')确保所有帖子都在单个查询中加载。它将查询次数减少到只有一个,从而提高了效率。

$users = User::with('posts')->get();
foreach ($users as $user) {
    // All posts are loaded along with users in a single query
    foreach ($user->posts as $post) {
        echo $post->title;
    }
}

其他优化技术

实施以下 Laravel 优化技术也有助于显着提高应用程序性能。

优化您的资产:

Laravel Mix 为 webpack 构建步骤提供了干净、流畅的 API。我们可以用它来缩小和合并CSS文件JavaScript。这减少了 HTTP 请求的数量。

// webpack.mix.js
const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .minify('public/js/app.js');

mix.sass('resources/sass/app.scss', 'public/css')
   .minify('public/css/app.css');

此示例编译 JS 和 SASS 文件并缩小它们,从而产生更小的文件和更快的加载时间。

数据库索引:

用于Index经常搜索或用作外键的列。这增强了数据库查询性能,并且Index可以通过迁移添加。

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('posts', function (Blueprint $table) {
    // Create an index for the 'title' column
    $table->index('title');

    // Create a unique index for the 'slug' column
    $table->unique('slug');

    // Foreign key index
    $table->foreign('user_id')->references('id')->on('users');
});

路由缓存:

路由缓存可以提高网站性能,尤其是在您有大量路由的情况下。

php artisan route:cache

这里我们创建一个路由缓存文件以加快路由注册速度。请注意,任何新的路由添加都需要再次运行此命令。

Laravel 优化的队列工作负载:

对于耗时的任务,例如发送电子邮件或某种图像处理,在后台运行这些任务是有益的。Laravel 的队列系统旨在对某些任务进行排队并异步处理它们。

首先,创造一个新的工作。

php artisan make:job ProcessImage

接下来,添加作业的行为

// app/Jobs/ProcessImage.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessImage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $image;

    public function __construct($image)
    {
        $this->image = $image;
    }

    public function handle()
    {
        // Process the image here
    }
}

现在分派工作。

ProcessImage::dispatch($image);

此代码片段将图像处理作业发送到默认队列,Laravel 处理其余的工作。

包起来

优化 Laravel 应用程序涉及缓存策略、高效数据库操作和智能资源加载的组合。通过实施这些技术,您可以显着减少加载时间和资源使用,从而获得更流畅的用户体验并可能提高 SEO 排名。

以下是一些可深入了解 Laravel 优化和性能的资源。

Laravel 官方文档: https: //laravel.com/docs/10.x/readme

Laracast: https: //laracasts.com/browse/all

最大化Laravel 性能:Web 开发人员的基本优化策略一文首先出现在TechTales上。

THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容