编程

Laravel 9 新特性预览

Martin Hwang 1078 2021-12-05 18:51:06

Laravel 9 是下一个 LTS 版本, 计划将于 2022 年初发布. 本文将概述所有目前已宣布的新特性及变更

 

Laravel 9 发布时间变更

Laravel v9 原计划于今年(2021年) 9 月份左右发布, 后来 Laravel 团队决定推迟到2022年1月份:

Laravel uses a variety of community-driven packages as well as nine Symfony components for a number of features within the framework. Symfony 6.0 is due for release in November. For that reason, we are choosing to delay the Laravel 9.0 release until January 2022.
By delaying the release, we can upgrade our underlying Symfony components to Symfony 6.0 without being forced to wait until September 2022 to perform this upgrade. In addition, this better positions us for future releases as our yearly releases will always take place two months after Symfony's releases.

(译者: 以上大意是 Symfony 6.0 于9月发布,为了在新版本中使用 Symfony 6.0 , 作出推迟发布的决定)

该变更将同时使得后续的大版本发布时间推后, 日程表如下:

  • Laravel 9:   2022年1 月
  • Laravel 10: 2023年1月
  • Laravel 11: 2024年1月

PHP 8 是 Laravel 9 的最低支持版本

由于Laravel 9 依赖 Symfony 6.0 , 而 Symfony 6.0 要求 PHP 最低版本是8. 因此 Laravel 9 会由同样的要求.

匿名迁移模板

Laravel 8.3 提供了一个叫匿名迁移(Anonymous Migrations)的新特性,  该特性避免迁移类名冲突

 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
  
 return new class extends Migration {
  
     /**
      * Run the migrations.
      *
    * @return void
     */
    public function up()
    {
       Schema::table('people', function (Blueprint $table) {
            $table->string('first_name')->nullable();
        });
   }
};

Laravel 9 发布时, 当你运行 php artisan make:migration 这个特性会成为默认选项

新的 Query Builder 接口

Laravel 9 将使用新的 Query Builder 接口, 详细的合并 PR 信息如下.

For developers who rely on type hints for static analysis, refactoring, or code completion in their IDE, the lack of a shared interface or inheritance between Query\Builder, Eloquent\Builder and Eloquent\Relation can be pretty tricky:

对于依赖在IDE中静态分析,重构及代码补全的类型提示的开发者,在Query\Builder, Eloquent\BuilderEloquent\Relation 之间缺少共同接口及继承,可能会很棘手

 return Model::query()
  ->whereNotExists(function($query) {
  // $query is a Query\Builder
 })
  ->whereHas('relation', function($query) {
  // $query is an Eloquent\Builder
  })
  ->with('relation', function($query) {
  // $query is an Eloquent\Relation
});

该特性添加了新的 Illuminate\Contracts\Database\QueryBuilder 接口以及 Illuminate\Database\Eloquent\Concerns\DecoratesQueryBuilder trait , 该 trait 替代已有的 __call  实现接口.

PHP 8 字符串函数

由于PHP 8 是最低要求, Tom Schlick 提交了一个 PR ,    在 \Illuminate\Support\Str 类内部使用str_contains(), str_starts_with()str_ends_with().

从 SwiftMailer 转到 Symfony Mailer

Symfony 弃用了 SwiftMailer, Laravel 9 将作相应变更, 使用 Symfony Mailer 作为邮件通信. 该变更会造成较大的破坏性改变, 请浏览对应 PR 了解更多详情.  Larave 9 更新指南正式发布时将包含相应向导.