Laravel 5.5 LTS 版本今天正式发布了!


Laravel 5.5 版本今天正式发布,该版本是下一代 LTS (Long Term Support) 版本,在功能特性上有重大改进和提升,就连 Laravel 框架作者 Taylor Otwell 自己也是在 Twitter 上对这一版本赞不绝口,甚为满意,下面就让我们先来一睹为快吧。

Whoops 扩展包

Laravel 4 中提供的 flip/whoops 再次回归,我们可以通过该扩展包在调试的时候进行优雅的堆栈信息追踪。

注:关于这个 Whoops 这个组件我们在深入探讨 PHP 错误异常处理机制及 Laravel 框架底层的相应实现这篇文章中也有提及和使用。

打印集合

另一个厉害的调试功能是集合打印方法:

<?php

Song::all()
    ->filter
    ->platinum
    ->dump()
    ->filter(function ($song) {
        return $song->released_on >= \Carbon\Carbon::parse('-10 years');
    })
    ->dd();

异常渲染

如果定义了一个公共的"响应"方法,异常就可以以响应的形式进行渲染。

在之前早期的 Laravel 版本中,要实现这一功能,你可以添加一个检查到 App\Exceptions\Handler::render() 方法,并基于异常类型发送响应。

在 Laravel 5.5 中,你只需要抛出异常,无需在处理器中添加任何逻辑就可以返回响应:

<?php

// throw new TerribleSongException($song) in a controller...

namespace App\Exceptions;

use App\Song;

class TerribleSongException extends \Exception
{
    /**
     * @var \App\Song
     */
    protected $song;

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

    /**
     * @param \Illuminate\Http\Request $request
     */
    public function render($request)
    {
        return response("The song '{$this->song->title}' by '{$this->song->artist}' is terrible.");    
    }
}

你还可以让异常类实现 Responsable 接口,这样 Laravel 也会自动响应。

Responsable 接口

实现了这个接口的类可以从控制器方法中返回;路由会在Illuminate\Routing\Router 中准备响应时检查 Responsable 实例。

下面是一个示例,我们将响应细节封装到了 NewSongResponse 对象中:

public function store(Request $request)
{
    $data = request()->validate([
        'title' => 'required',
        'artist' => 'required',
        'description' => 'required',
        'duration' => 'required|numeric',
        'released_on' => 'required|date_format:Y-m-d',
        'gold' => 'boolean',
        'platinum' => 'boolean',
    ]);

    $song = new Song($data);
    $song->save();

    return new NewSongResponse($song);
}

下面是实现了 Responsable 接口的 NewSongResponse 类代码:

<?php

namespace App\Http\Responses;

use App\Song;
use Illuminate\Contracts\Support\Responsable;

class NewSongResponse implements Responsable
{
    /**
     * @var \App\Song
     */
    protected $song;

    /**
     * @param \App\Song $song
     */
    public function __construct(Song $song)
    {
       $this->song = $song; 
    }

    public function toResponse($request)
    {
        if ($request->wantsJson()) {
            return response()
                ->json($this->song)
                ->header('Location', route('songs.show', $this->song))
                ->setStatusCode(201);
        }

        return redirect()
            ->route('songs.show', $this->song);
    }
}

在这个简单的例子中,如果是通过 AJAX 发送请求的话你可以自动返回 JSON 响应,并默认重定向到 songs.show 路由。

请求验证方法

在之前的版本中,你可以传递请求实例到某个控制器的 $this->validate() 方法:

$this->validate(request(), [...]);

现在,你只需在请求对象上调用验证方法即可:

$data = request()->validate([
    'title' => 'required',
    'artist' => 'required',
    'description' => 'required',
    'duration' => 'required|numeric',
    'released_on' => 'required|date_format:Y-m-d',
    'gold' => 'boolean',
    'platinum' => 'boolean',
]);

这种风格调用验证方法的另一个好处是返回值就像 Request::only(),只返回验证调用中提供的字段。只返回验证字段的使用起来很方便,从而避免了 Request::all()

自定义验证规则对象和闭包

我个人最喜欢的新特性是新的自定义验证规则对象和闭包,创建自定义规则对象是通过 Validator::extend 创建自定义规则之外的另一种方法,不过这种单独定义的好处是规则逻辑看上去更加清晰。下面是一个示例:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CowbellValidationRule implements Rule
{
    public function passes($attribute, $value)
    {
        return $value > 10;
    }

    public function message()
    {
        return ':attribute needs more cowbell!';
    }
}

下面是使用上述验证规则的示例:

<?php

request()->validate([
    'cowbells' => [new CowbellValidationRule],
    'more_cowbells' => [function ($attribute, $value, $fail) {
        if ($value <= 10) {
            $fail(':attribute needs more cowbell!');
        }
    }]
]);

闭包风格的验证规则需要传入属性名和值,以及一个失败参数用于验证失败的场景。在你最终将自定义验证逻辑提取到专门的规则对象之前,闭包是一个很好的实验方式,或者用作一次自定义验证需要。

要创建自定义验证规则对象,可以使用新提供的 make:rule 命令:

$ php artisan make:rule MyCustomRule

已登录和游客Blade指令

Laravel 5.5 新提供了条件指令 @auth@guest,在此之前,要在 Blade 模板中检查用户是否登录,需要这么做:

@if(auth()->check())
    {{ -- 已登录 --}}
@endif

@if(auth()->guest())

现在你可以这么做来实现同样的功能:

@auth
    Welcome {{ user()->name }}!
@endauth

@guest
    Welcome Guest!
@endguest

前端预置

当你创建一个新项目的时候,Laravel 5.5 默认为你提供了 Vue.js 脚手架。在 Laravel 5.5 中你现在可以从预置组件中挑选一些你所需要的,然后通过 Artisan 命令 preset 移除所有其他前端脚手架。

如果你查看帮助,可以看到可以选择 "none","bootstrap","vue" 或者 "react":

php artisan help preset
Usage:
  preset <type>

Arguments:
  type    The preset type (none, bootstrap, vue, react)

# Use react
$ php artisan preset react

# Clear scaffolding
$ php artisan preset none

分离工厂文件

之前版本的 Laravel 工厂文件都是定义在一个 ModelFactory.php 文件中,现在你可以为每个模型创建不同的文件,你可以在创建一个新模型时创建对应的工厂文件:

$ php artisan make:model -fm Post

# Or you can create a controller, migration, and factory
$ php artisan make:model --all

还可以直接通过 make:factory 命令创建工厂文件:

$ php artisan make:factory --model=Example ExampleFactory

迁移命令 migrate:fresh

Laravel 5.5 新提供的 migrate:fresh 命令在开发中可以很方便的用于创建新的干净的数据库环境,该命令会将数据库中的所有数据表都删除然后运行所有迁移文件。

你可能之前对 migrate:refresh 命令很熟悉,它是用于回滚所有迁移然后重新运行。不过在开发过程中你通常只是想删除数据表,获得一个干净的数据库,然后再运行迁移。

更多

更多新特性及其使用细节,可关注官方文档,也可以追接下来 Laravel 学院为你提供的全新 Laravel 5.5 中文文档,我们将不在纯翻译官方文档,而是以示例化教程的方式尽可能让你学会每一个知识的细节。

声明:本文整理翻译自Laravel News

点赞 取消点赞 收藏 取消收藏

<< 上一篇: 又一个基于 Laravel 5.2 开发的后台管理系统

>> 下一篇: 阿里云 Ubuntu 14.04 LTS 中将 PHP 从 5.5 升级到 7.x 完整笔记