Major differences and new features between Laravel 5 and Laravel 4.2

Source: Internet
Author: User

Major differences and new features between Laravel 5 and Laravel 4.2

It has been more than a month since when Laravel 5.0 was released (in fact, the latest version is v5.0.16). Some friends are still using the familiar 4.2, and some are exploring the new experience brought by 5.0. Next I will mainly introduce the differences between this 5.0 version and the previous 4.2 version, as well as some of my personal suggestions and ideas on using Laravel 5.0.

Recommended audience: I have written a program with Laravel 4.2 and read the Laravel 5.0 documentation.

The following titles briefly summarize the main features. If you are familiar with this section, you can skip this section.

A clearer "directory structure 」

Oldapp/modelsThe directory has been completely removed, but we recommend that you create a new models directory app/models and add a namespace. All the code is stored inappDirectory, which is used by defaultAppThis namespace. However, the default namespace can use commands.php artisan app:name Artisan(The changes here are not only the namespace in the php file, but also strings containing namespaces in some programs, do not think that you can modify all namespaces by manually modifying the namespace of the file ).

Controllers, middleware (middleware), and requests are now stored inapp/HttpBecause they are related to the HTTP transport layer of the application.

Newapp/ProvidersDirectory replaced earlier version Laravel 4.xapp/start. These service providers have many methods related to starting applications, such as error processing, logging, route loading, and more. Of course, you can freely create new service providers to applications.

Some custom exception classes can be placed inapp/ExceptionsAndHandler.phpFile.

Some custom events can be stored inapp/Events.

You can alsoappAddProviders,RepositoriesYou need folders to classify your program files so that your program directory and logic are clearer.

The language files and views of the application are movedresourcesDirectory. And your project'sjsAndcssPut the file here, and then useElixirTo process and automatically storepublicFolder for your project reference.

Complicated but more standard namespace 」

Namespace does make many PHPer "stunned", but it is a bit exaggerated, but many of them are overwhelmed. In Laravel 5.0, namespace uses the PSR-4 specification, as long as you follow this, it will not be wrong. In addition, Laravel 4.2 is free of errors that you have made over and over again, and you finally find that you forget to add a new class file and then executecomposer dumpautoloadThis command is troublesome.

Model

This topic is specifically mentioned in the namespace.modelThere is a reason. In Laravel 4.2.2app/All files in the bucket are named in the global namespace.EloquentYou may writereturn $this->hasOne('Phone');.

But in Laravel 5.0, you need to changereturn $this->hasOne('App\Phone');It looks like this.

Route

ActuallyrouteHereurlThe corresponding controller and method strings are also added with namespaces by default.App\Providers\RouteServiceProviderIn this file, the default namespace isApp\Http\Controllers. However, if youapp/Http/ControllersThecontrollerFolder to classify yourcontrollerWhen writing a route, you need to add additional processing. For example

Route::controllers([    'auth' => 'Auth\AuthController',    'password' => 'Auth\PasswordController',]);
Note that

Because all your programs are inApp\***In such a namespace, if you use a string variable as the class name, you must write the string as a complete class name with a namespace. Otherwise, an error will be reported that the class cannot be found. For example

# Possible format in Laravel 4.2: $ myClassName = 'Dog'; $ obj = new $ myClassName (); // In Laravel 5.0, an error is reported. # In L5, you need to change it to $ myClassName = 'app \ Models \ Dog '; $ obj = new $ myClassName ();
"Route" with improved performance 」

It is true that before Laravel 5.0, the situation of over 100 routes is very embarrassing, and efficiency is indeed a problem. In Laravel 5.0, the cache was decisively added to improve efficiency. For some projects that are slightly larger, the benefits are not small. Rememberphp artisan route:cacheThis command.

Middleware is better than Filters

Middleware has to be said to be a good thing. Those who have used other language frameworks may find the importance of this thing. Middleware allows a request to enter yourroute.phpIng incontroller@methodBefore using this method, we will handle it for you. For example, to process HTTP session read/write, determine whether the application is in maintenance mode, check cross-site Request Forgery (CSRF) flag, and other functions, this includes everything you think you need to handle before entering the controller, as well as redirection, error reporting, logging, and Request processing. So as to ensure that yourcontrollerAs you wish.

In the use of Laravel 5.0, you can simply understand that the filter of Laravel 4.2 is replaced by the middleware, but the middleware is far more powerful and more useful than the filter of Laravel 4.2.

"Service provider" will give you more help

In fact, service providers are used in Laravel 4.2, especially in some dependencies.laravel frameworkBut it is not widely used in programming. Laravel 5.0 emphasizes and improves the practicability of this part. Even with the newapp/ProvidersDirectory replaces Laravel 4.2'sapp/startFile. These service providers have many methods related to starting applications, such as error processing, logging, route loading, and more. Of course, you can freely create new service providers to applications.

Simply put, the service provider does something about starting and registering applications. A typical example is to load the corresponding extensions based on the environment.

// AppServiceProvider.phppublic function register(){    $this->app->bind(        'Illuminate\Contracts\Auth\Registrar',        'App\Services\Registrar'    );    if ($this->app->environment('production')) {        $this->app->register('App\Providers\ProductionErrorHandlerServiceProvider');    } else {        $this->app->register('App\Providers\VerboseErrorHandlerServiceProvider');    }}

We usually write programs that are more widely used inproviderOfregister()To bind the dependency injection, andboot()Method to bind some listening events.

In Laravel 5.0, dependency injection is enhanced to make it easier for everyone to use. The following 「Context binding"And 「Controller dependency InjectionIs a new feature.

Context binding

In Laravel 4.2, If you bind a class to an interface, the implementation of this class will always be injected according to the interface prompt, when you want to implementInject different classes using the same interfaceIt is impossible, because Laravel 4.2 only allows the implementation of one interface to be bound to this interface, unless you give up binding the class to the interface, the injection class name is explicitly specified, but this violates the flexibility of dependency injection.

In Laravel 5.0, You can flexibly inject data according to the context, for example

$this->app->when('App\Handlers\Commands\CreateOrderHandler')          ->needs('App\Contracts\EventPusher')          ->give('App\Services\PubNubEventPusher');

In this way, you canCreateOrderHandlerAccording to the prompted InterfaceEventPusherTo injectPubNubEventPusher.

Controller dependency Injection

If you want to create a new uploaded video in Laravel 4.2controllerOfcreate($id)Method InjectionMoiveCreaterObject (for exampleMoiveCreaterThis class contains methods for connecting to the video server and creating directories, obtaining thumbnails, and video conversion.) This is not possible becauserouteA parameter is bound, and you cannot write it into this method. The solution is to inject__constructMethod and assign it to the variables in the class.

You can write in Laravel 5.0 as follows,create(MoiveCreater $moveCreater, $id). Does this look cool? Haha

More useful "help functions 」

Because namespace is used in the programcontrollerIt is inconvenient to use some common class operations, because it will reference a lot of class namespaces, for example,\View \Response \ConfigWait, or you can useuse.

We recommend that you use Laravel 5.0view() response() config()To perform your operations elegantly. If you want to know all such functions or implementation methods, let's take a look.

Command commands that can encapsulate your logic 」

Note: commands and console command are two different tasks..

I believe thatcontrollerWith the development of programs, there will be more and more input processing, business logic, input processing, and so on,controllerIt will be huge and bloated, which will affect the beauty of the program structure and the original intention of laravel.

PasscommandEncapsulate some business logic so that you can onlycontrollerThe business logic used incontroller. PaircommandThe execution can be synchronous or in the queue form.

View template for security considerations 」

In Laravel 5.0{{ }}In Laravel 4.2{{{ }}}In Laravel 5.0{!! !!}This complicated statement replaces the simple one in Laravel 4.2.{{ }}. It is obvious that we recommend that you output all the escape security characters.

Simple and clear configuration file 」

When we first came into contact with Laravel 4.2, we may still be touched by the fact that different configuration files can be configured in different environments of Laravel 4.2. However, over time, I believe that many people use only one configuration file, just like me. As a result, the configuration of Laravel 4.2 is cumbersome.

Individual configurations in Laravel 5.0 are in the root directory.envIf the file is in, you can copy a copy as a template for other colleagues to copy and modify it from the row. This operation is undoubtedly the most concise and convenient.

Integrated Gulp's "Elixir" for front-end considerations 」

Currently, the most popular frontend development method is to usegulpTo merge, compress, and Control Versions of front-end files. In Laravel 5.0,ElixirAllows you to store js, css, and other files inresourcesFoldergulpThe generated file is automatically published to the public folder. When referencingelixir()The method is automatically processed.publicWhether the path in the folder is a js or css file with a version number added.

Last

The above describes some of the differences and new functions that I think are commonly used and important. Of course, the difference between Laravel 5.0 and Laravel 4.2 is much more than that. There are more details and functions, for more information, see my other article Laravel 4.2's comprehensive introduction to Laravel 5, which describes how to implement some features already in Laravel 4.2 in Laravel 5.0.

Deploy Laravel using Nginx in Ubuntu

Deploying Laravel 14.04 using Nginx on Ubuntu 5.0

This article permanently updates the link address:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.