laravel5.2.15_Laravel 5.5的新功能

laravel5.2.15

At the time of this writing, Laravel 5.5 is not released yet. It is slated, as the next major release, for release in July 2017. To play around with new features and changes, you need to grab the dev release of Laravel using this Laravel Installer command:

在撰写本文时,Laravel 5.5尚未发布。 它计划于2017年7月发布,作为下一个主要版本。要试用新功能和更改,您需要使用以下Laravel Installer命令获取Laravel的开发版本:

laravel new project --dev

赶快使用PHP 7.0+ ( Get Ahead with PHP 7.0+ )

Laravel 5.5 will require PHP 7.0+. Along with developer features, PHP 7 includes speed improvements which will decrease CPU load by half. So, you should definitely make this upgrade. And if you are using Laravel 5, making this upgrade will be a lot easier since you using the latest version of PHP.

Laravel 5.5将需要PHP 7.0+。 除开发人员功能外,PHP 7还包括速度改进,它将CPU负载减少一半。 因此,您绝对应该进行此升级。 而且,如果您使用的是Laravel 5,则由于使用的是最新版本PHP,因此升级起来会容易得多。

下一个LTS(长期支持)版本 ( The Next LTS (Long Term Support) Release )

After Laravel 5.1, Laravel 5.5 is scheduled to be the next LTS release. This includes two years of bug fixes and three years of security updates.

在Laravel 5.1之后,Laravel 5.5被安排为下一个LTS版本。 这包括两年的错误修复和三年的安全更新。

欢迎回来:哎呀! ( Welcome Back: Whoops! )

Whoops PHP Package

Whoops, an error-handling framework, which used to be used by Laravel 4, was removed with the release of Laravel 5.0. But with Laravel 5.5, it's coming back pre-installed. What Whoops actually does is that it makes the annoying PHP errors and exceptions a little less annoying by changing how they appear. As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception. And not forgetting to mention, it has zero dependencies (currently('pre-laravel-55')).

Larop 5发行时已删除了曾经由Laravel 4使用的错误处理框架Whoops。 但是随着Laravel 5.5的出现,它已经预装了。 Whoops实际上所做的是通过更改它们的出现方式,使烦人PHP错误和异常少了一些烦人。 正如您在图像中所看到的,它处理了发生错误或异常的文件行,并追溯到操作开始。 值得一提的是,它具有零依赖关系(当前('pre-laravel-55'))。

“ vendor:publish”得到提供者提示 ( "vendor:publish" Gets a Provider Prompt )

In previous versions of Laravel, running the vendor:publish command will publish views, configs, migrations and other resources of all vendors. But in Laravel 5.5, running this command will prompt you to select a provider or tag, making it easier to publish only the ones you want. You can also bypass this prompt by specifying the --all' or '--provider' flag with thepublish` command.

在以前的Laravel版本中,运行vendor:publish命令将发布所有供应商的视图,配置,迁移和其他资源。 但是在Laravel 5.5中,运行此命令将提示您选择提供程序或标记,从而使仅发布所需的更容易。 您也可以通过--all' or '--provider' flag with the publish`命令指定--all' or '--provider' flag with the来绕过此提示。

电子邮件主题 ( Email Themes )

Laravel 5.5 adds the ability to specify a custom theme directly to Mailable classes. You can create a CSS style-sheet like this:

Laravel 5.5增加了直接向Mailable类指定自定义主题的功能。 您可以创建一个CSS样式表,如下所示:

touch resources/views/vendor/mail/html/themes/batman.css

And then specify this filename as a property in your Mailable class.

然后将此文件名指定为Mailable类中的属性。

class SendInvoice extends Mailable
{
    protected $theme = 'batman';
    ...
}

将可发送邮件呈现给浏览器 (Rendering Mailables to the Browser)

It can be tedious to test your email templates across email clients. One way to test them is to render them to the browser so that you can make instant changes. But it is not an easy task. Luckily, Laravel 5.5 adds the facility to display them directly from your routes.

在电子邮件客户端之间测试电子邮件模板可能很繁琐。 测试它们的一种方法是将它们呈现给浏览器,以便您可以立即进行更改。 但这不是一件容易的事。 幸运的是,Laravel 5.5添加了直接从您的路线显示它们的功能。

You can create a Mailable like this:

您可以这样创建一个Mailable:

php artisan make:mail UserWelcome --markdown=emails.user.subscription.canceled

And then render it through a route:

然后通过一条路线渲染它:

Route::get('/no/way', function () {
    return new App\Mail\UserSubscriptionCanceled();
});

There are other tools like Litmus, which solve this problem, but they are pretty expensive relative to this tediously trivial task.

还有其他工具,例如Litmus,可以解决此问题,但相对于这项繁琐的琐事而言,它们的成本很高。

新移民 ( Fresh Migrations )

Laravel 5.5 adds another Artisan command to the migrate: namespace. This is similar to migrate:refresh but rather than rolling back your existing migrations, it drops all tables and migrates them from start. The difference between rolling back migrations and dropping tables is that rolling back migrations runs the drop method for each of them. Whilst, the migrate:fresh command simply drops all off of the tables and starts from scratch.

Laravel 5.5将另一个Artisan命令添加到migration migrate:名称空间。 这类似于migration migrate:refresh但不回滚现有的迁移,而是删除所有表并从头开始迁移它们。 回滚迁移删除表之间的区别在于,回滚迁移对每个迁移都运行删除方法。 同时, migrate:fresh命令只是将所有表从表中删除并从头开始。

自动包装发现 ( Automatic Package Discovery )

In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases. Laravel 5.5 adds the ability for packages to automatically register service providers and add aliases through the package's composer.json file like this:

在Laravel 5.4及其之前的所有版本中,拉动Laravel软件包都需要注册其服务提供商并添加别名。 Laravel 5.5为程序包增加了自动注册服务提供商并通过程序包的composer.json文件添加别名的功能,如下所示:

"extra": {
    "laravel": {
        "providers": [
            "The\\Dark\\Knight\\BatmanServiceProvider"
        ],
        "aliases": {
            "Bar": "The\\Dark\\Knight\\Batman"
        }
    }
}

If you are a package developer, then things can't be much easier for your package users.

如果您是程序包开发人员,那么对于您的程序包用户而言,事情就简单多了。

前端预设 ( Frontend Presets )

Out of the box, Laravel includes some CSS and JavaScript scaffolding to help accelerate coding the nitty-gritty. Although you could remove them and start over with your personal preferences, the suggestion was only limited to the Vue framework. Laravel 5.5 introduces 3 frontend presets: Bootstrap, Vue, React and an option choose your own. With Vue being the default preset, you can change the preset to react using this command:

开箱即用,Laravel包含一些CSS和JavaScript支架,以帮助加快对细节的编码。 尽管您可以删除它们并从个人喜好开始,但是建议仅限于Vue框架。 Laravel 5.5引入了3个前端预设:Bootstrap,Vue,React和一个选项供您选择。 将Vue作为默认预设,您可以使用以下命令更改预设以做出React:

php artisan preset react

You can change react in the above command to vue, bootstrap or none based on your preference.

您可以根据自己的喜好在上面的命令中将react更改为vue,bootstrap或none。

错误页面:设计改进 ( Error Pages: Design Improvement )

In Laravel 5.5, a little change is made in the design of the error pages like 404 or 50* errors: there are some design additions with Flexbox getting the error message centered on the page.

在Laravel 5.5中,错误页面的设计进行了一些更改,例如404或50 *错误:Flexbox进行了一些附加设计,使错误消息集中在页面上。

Before Laravel 5.5:

在Laravel 5.5之前:

Before Laravel 5.5

In Laravel 5.5:

在Laravel 5.5中:

In Laravel 5.5

自定义错误报告 ( Custom Error Reporting )

Laravel 5.5 adds support for defining a report method on any custom exception. In Laravel 5.4, you had to check in the Handler class's report method if a particular exception was thrown. So that you could do something like send an email or report to your app's monitoring service. You were doing something like this:

Laravel 5.5增加了对定义任何自定义异常的报告方法的支持。 在Laravel 5.4中,您必须检入Handler类的report方法,是否抛出了特定异常。 这样您就可以执行诸如向应用程序的监视服务发送电子邮件或报告之类的操作。 您正在执行以下操作:

...

class Handler extends ExceptionHandler
{
    ...

    public function report(Exception $exception)
    {
        if ($exception instanceof CustomException) {
            // Send email
        }

        parent::report($exception);
    }
}

But with Laravel 5.5, you can get rid of this and register the report method on your custom exception class. Laravel checks to see if there is a report method on your exception class and if it does: calls it.

但是使用Laravel 5.5,您可以摆脱它,并在自定义异常类上注册report方法。 Laravel检查您的异常类上是否有一个报告方法,是否包含:调用它。

简化的请求验证 ( Streamlined Request Validation )

Laravel 5.5 comes with two changes to Request feature. One is that you can now directly call the validate method on your Request instance. So instead of using the controller validator, you can call the validator on your Request instance. You also no longer need to pass the request as the first argument to the validator. Here is an example:

Laravel 5.5对请求功能进行了两项更改。 一种是您现在可以直接在Request实例上调用validate方法。 因此,您可以在Request实例上调用验证器,而不是使用控制器验证器。 您也不再需要将请求作为第一个参数传递给验证程序。 这是一个例子:

...

public function store()
{
    request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    return Post::create(request(['title', 'body']));
}

The second change made is that the validator returns the request data which you can store in a variable and pass on to the create method of the model.

进行的第二个更改是验证器返回请求数据,您可以将其存储在变量中并传递给模型的create方法。

...

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

You need to be careful with this since the data returned by the validator will only contain the fields defined in the rules. This adds a little security but you can loose data if some fields were not defined rules for. To avoid this trap, you can add the field with an empty rule like this:

您需要注意这一点,因为验证器返回的数据将仅包含规则中定义的字段。 这增加了一点安全性,但是如果未为某些字段定义规则,则可以丢失数据。 为避免此陷阱,您可以使用以下空规则添加字段:

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required',
        'fieldWithNoRules' => '',
        'andAnotherOne' => ''
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

异常助手功能 ( Exception Helper Functions )

Coming to Laravel 5.5 are two new helper functions to help you throw exceptions more elegantly. They are: throw_if and throw_unless, and they do exactly what they say. If you want to throw an exception based on a condition then these may help you reduce a conditional block to a single line. They both accept three arguments with the third being optional. First one is a boolean, second is the exception class and third is the exception message passed in case if you didn't pass with the instantiation of the exception in the second argument. throw_if throws the exception if the boolean is positive and throw_unless throws the exception when the boolean is negative. Here are the examples:

Laravel 5.5新增了两个辅助功能,可以帮助您更优雅地引发异常。 它们是: throw_ifthrow_unless ,它们完全按照他们说的去做。 如果要基于条件引发异常,则这些可以帮助您将条件块减少为一行。 它们都接受三个参数,第三个是可选的。 第一个是布尔值,第二个是异常类,第三个是传递的异常消息,以防万一您没有在第二个参数中实例化异常。 throw_if抛出异常,如果布尔是积极的, throw_unless抛出异常时,布尔为负。 以下是示例:

// For `throw_if:

$foo = true;
throw_if($foo, new BarException('Foo is true'));
// or 
throw_if($foo, BarException::class, 'Foo is true');

// For `throw_unless:

$phoo = false;
throw_unless($phoo, new BazException('Phoo is false'));
// or
throw_unless($phoo, BazException::class, 'Phoo is false');

自定义验证规则 ( Custom Validation Rules )

Laravel 5.5 is coming with a new feature for adding custom validation rules. Custom validation rules are nothing new but with Laravel 5.5 you can have a dedicated class to handle the validation. To define a custom validation rule, you need to create a class with two methods: passes and message. You can place this class anywhere like in the App\Rules namespace. The passes method accepts two arguments: attribute and value, which you can use to validate the field.

Laravel 5.5附带了一项用于添加自定义验证规则的新功能。 自定义验证规则并不是什么新鲜事物,但是使用Laravel 5.5,您可以拥有一个专用的类来处理验证。 要定义自定义验证规则,您需要使用两个方法创建一个类: passesmessage 。 您可以将此类放置在App\Rules命名空间中的任何位置。 pass方法接受两个参数:attribute和value,可用于验证字段。

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{   
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // must return true or false for the validation to pass or fail
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // return a string here for the failing condition
    }
}

Your custom rule should implement the Laravel's Illuminate\Contracts\Validation\Rule contract. You can use this custom validation rule anywhere like in a Form Request class or in the controller validator or the validator from the Request instance. If you are using a custom rule then you can't pass a string with rules separated by a comma. You need to pass each rule as a single element grouped in an array like this:

您的自定义规则应实现Laravel的Illuminate\Contracts\Validation\Rule合同。 您可以在Form Request类中,控制器验证器或Request实例中的验证器中的任何地方使用此自定义验证规则。 如果您使用的是自定义规则,则不能传递带有逗号分隔的规则的字符串。 您需要将每个规则作为单个元素传递到数组中,如下所示:

$request->validate([
    'someField' => [
        'required', 'min:4', new CustomRule()
    ]
]);

You may also inject any dependency to the constructor if you want. This class-based approach makes custom validation a lot easier.

如果需要,您还可以将任何依赖项注入到构造函数中。 这种基于类的方法使自定义验证变得更加容易。

模型工厂发电机 ( Model Factory Generators )

In Laravel 5.5 you can easily generate model factories with a new Artisan command called make:factory. Here is an example:

在Laravel 5.5中,您可以使用名为make:factory的新Artisan命令轻松生成模型工厂。 这是一个例子:

php artisan make:factory PostFactory

This will make a new file called PostFactory.php in the database/factories folder. What makes it a lot better is that you can also generate a factory while making a model.

这将在database / factories文件夹中创建一个名为PostFactory.php的新文件。 使它变得更好的是,您还可以在创建模型时生成工厂。

php artisan make:model Post -f

You may also pass the -c flag to add a controller and the -m flag to add a migration. This will help in quickly whipping up a resource.

您也可以传递-c标志以添加控制器,并传递-m标志以添加迁移。 这将有助于快速补充资源。

杂记 ( Miscellany )

One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it's related to CSRF.

一个较小的更改是,如果您忘记在表单中包含CSRF字段,那么它将为您提供更好的不活动错误页面。 因此,如果您看到类似的内容,请确保它与CSRF有关。

There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.

还有另一个较小的更改,它将帮助您构建API。 现在,如果发生错误,您将获得JSON堆栈跟踪而不是HTML标记。 如果您使用的是诸如Postman之类的工具,那么它看起来比丑陋的标记要漂亮得多。

结论 ( Conclusion )

I hope this guide gets you prepared for the forthcoming goodness. So, This is all there is coming to Laravel 5.5.

我希望本指南能使您为即将到来的善良做好准备。 所以,这就是Laravel 5.5的全部功能。

Happy Coding!

编码愉快!

翻译自: https://scotch.io/tutorials/whats-new-in-laravel-55

laravel5.2.15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值