Waited for the release of Laravel 5

Laravel logoHello! It seems that the residents of Habrahabr are still skeptical of the eloquent php framework Laravel from Taylor Otwell . Unfortunately, no one ever covered yesterday's release of the new 5th version. I will try to make up for this shortcoming. I will not talk about what kind of regular framework this is and what bicycles are in his garage, but I will cover only those moments that were affected by the change. Basically, the article will be a free translation of release notes from the official site. I did not translate part of the concepts and terms so that the meaning would not be lost.

Updated design of the official website


I remember when I first found out about Laravel, I dropped the link to off. site colleague to share his enthusiasm, but after a couple of minutes he heard the categorical "too much pink." From now on, such statements should not take place. The new design got rid of the big pink hat at the top of the main page, leaving only a few patriotic (in the context of the framework) headings calling for the use of a personalized given solution.

The documentation page has retained its former appearance, but has become more logical in terms of version separation. Previously, the development version was marked as dev, now it is called master, which corresponds to the name of the branch on github .

File structure


The app / models folder has been deleted . Now all the code regarding your application is stored in the app folder in the App namespace (hello psr-4!). The standard namespace can be changed by Artisan with the app: name command .

Controllers, middleware, and requests (a new class type in Laravel 5.0) are grouped in the app / Http folder , as these classes belong to the application HTTP layer. Instead of a single file with filters, each middleware (an alternative to filters, something between the request and the transition to the controller) acquired its own class.

The classes in the app / Providers folder came to replace the files in the app / start folder. These service providers provide loading classes into the application, such as error handling, logging, loading routes, etc. In the same place, you can create your own service providers.

Multilingual and presentation files have been moved to the resources folder.

Contracts


All major Laravel components implement the interfaces found in the illuminate / contracts repository. This repository has no external dependencies. With a convenient, centralized set of interfaces, you can use them for decoupling, and the implementation of dependencies will serve as an excellent alternative to facades.

Documentation .

Route cache


If your application consists solely of route-controllers, you can use the new Artisan route: cache command to significantly speed up the loading of the route map. It makes sense to use this feature on applications with 100 or more routes to increase the download speed of this part of the application.

Route middleware


Laravel 4 filters were replaced by HTTP middleware in Laravel 5, and the familiar standard authorization filters and CSRF protection filters were rewritten in a new way. Middleware provides a single, consistent interface for replacing any kind of filter, allowing you to conveniently examine and reject the request before it is submitted to the controller for processing.

Documentation .

Controller Method Injection


In addition to the existing constructor injection, you can now specify dependencies (orig .: type-hint dependencies) in controller methods. The IoC container will automatically inject dependencies, even if the route contains other parameters:
public function createPost(Request $request, PostRepository $posts)
{
    //
}


Authentication Scaffolding


Registration, user authorization, as well as password recovery are now available “out of the box”, and the corresponding views are located in resources / views / auth . In addition to this, the migration of the users table comes with the framework. The inclusion of these simple resources allows you to quickly develop prototypes without spending time organizing authorization. Authorization interfaces are available on the auth / login and auth / register routes . The App \ Services \ Auth \ Registrar service is responsible for validating and creating users.

Event objects


Now events (orig .: Events) can be defined as classes, instead of strings, for example:
class PodcastWasPurchased {
    public $podcast;
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }
}

An event can be sent out (original: dispatched), as before:
Event::fire(new PodcastWasPurchased($podcast));

The event handler will receive an event object, instead of a list of data:
class ReportPodcastPurchase {
    public function handle(PodcastWasPurchased $event)
    {
        //
    }
}


Documentation .

Commands / queueing


In addition to queues (original: queue job format) supported in Laravel 4, Laravel 5 allows you to present a queue as simple command objects. These commands are located in the app / Commands folder . Example:
class PurchasePodcast extends Command implements SelfHandling, ShouldBeQueued {
    use SerializesModels;
    protected $user, $podcast;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(User $user, Podcast $podcast)
    {
        $this->user = $user;
        $this->podcast = $podcast;
    }
    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        // Handle the logic to purchase the podcast...
        event(new PodcastWasPurchased($this->user, $this->podcast));
    }
}

The Laravel base controller uses the new DispatchesCommands flag (orig .: trait), which makes it quite simple to send commands for execution:
$this->dispatch(new PurchasePodcastCommand($user, $podcast));

Commands can also be used for tasks that are executed synchronously (do not line up). In fact, using commands is a great opportunity to encapsulate the complex tasks your application solves.

Documentation .

Database queue


The database queue driver is now available out of the box. Provides a simple local driver that does not require additional dependencies outside the database.

Laravel scheduler


Previously, in order to plan the execution of a console command, developers had to “hang” each of them on a cron, which caused a lot of headache. Due to the fact that this process does not occur in the application ecosystem, it was required to connect to the server via SSH (or through the web interface) and manually control the process. Now everything has become much easier. The task scheduler in Laravel allows you to quickly and easily add scheduled tasks inside the application itself and now it requires only one cron task!

It looks something like this:
$schedule->command('artisan:command')->dailyAt('15:00');


Documentation .

Tinker / psysh


The php artisan tinker team now uses Psysh from Justin Hileman (a more robust REPL for PHP). If you liked using Boris in Laravel 4, then you will certainly love Psysh. It even works under Windows! To start, write in the terminal:

php artisan tinker


Dotenv


Instead of the confusing variety of subfolders with environment configurations, Laravel 5 uses DotEnv from Vance Lucas. This library provides a super easy way to manage settings for a specific runtime environment and allows you to define your environment on the fly.

Documentation .

Laravel elixir


Jeffrey Way's Laravel Elixir provides a simple and expressive interface for assembling resources (orig .: assets). If you were afraid to start learning Grunt or Gulp - now it will be easy. Elixir is an interlayer for Gulp for building Less, Sass, and CoffeeScript, as well as for concatenating files and caching based on versions. He can even run tests!

Documentation .

Laravel socialite


Laravel Socialite is an optional package compatible with Laravel 5.0+, which allows you to completely implement authorization using the OAuth protocol. Currently supports Facebook, Twitter, Google, and GitHub. What does it look like:
public function redirectForAuth()
{
    return Socialize::with('twitter')->redirect();
}
public function getUserFromProvider()
{
    $user = Socialize::with('twitter')->user();
}


Documentation .

Flysystem integration


Now Laravel comes with the most powerful Flysystem file system , an abstraction layer that provides seamless integration with local FS, Amazon S3, and Rackspace cloud storage - all in one single and elegant API! Storing files on Amazon S3 is now so simple:
Storage::put('file.txt', 'contents');


Documentation .

Form requirements


Laravel 5.0 introduces "form requests" (orig. Form requests), which are extended by the Illuminate \ Foundation \ Http \ FormRequest class. These request objects can be embedded in controller methods to validate user input. An example of a simple FormRequest :
 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ];
    }
    public function authorize()
    {
        return true;
    }
}


After the class is defined, we can “hint” (orig .: type-hint) about it in the controller method:

public function register(RegisterRequest $request)
{
    var_dump($request->input());
}


When the Laravel IoC container determines that the implemented instance of the FormRequest class , the request will automatically be verified (original: validated). This means that if the controller's (original: action) method is called, you can be sure that the user input has been successfully verified in accordance with the rules defined in FormRequest . Even more, if the request is invalid, a redirect (which you can configure) will automatically work where the quick message (original: flash message) will be sent to the session, or in a JSON string. Form validation has never been easier!

Documentation .

Simple Controller Request Validation


The base controller in Laravel 5 can now use the ValidatesRequests attribute (orig .: trait). This feature provides a simple method for validating an incoming request. If FormRequests is too cumbersome for your application, take a look at this:
public function createPost(Request $request)
{
    $this->validate($request, [
        'title' => 'required|max:255',
        'body' => 'required',
    ]);
}


If validation fails, an exception will be thrown and the appropriate HTTP headers sent back to the browser. Also, validation errors “flare up” (orig .: flashed) into the session. If the request was sent by AJAX, Laravel will automatically convert these errors to a JSON string.

Documentation .

New generators


On the occasion of updating the framework structure, new Artisan generator commands have been added. For more detailed information write in the terminal
php artisan list


Configuration cache


Now you can cache all configuration files by combining them into one file with the command:
php artisan config:cache


Symfony vardumper


The popular dd helper, which “dumps” debugging information, has been updated and now uses the incredible Symfony VarDumper, which provides color output and even collapsing / expanding arrays. Just try this:
dd([1, 2, 3]);


On the occasion of the release of the 5th version, Jeffrey Way opened free access to video tutorials, in which it clearly explains the new features. To what point is unknown. You can watch the video online, but the download button leads to your personal account, so if you want to watch later, inspect the video player in search of a direct link.

There is also a series of articles by Matt Stauffer , if you like to read.

Laravel is a great, fresh framework. It accumulates in itself the best OOP practices and existing components, it is a designer to design on which is easy and pleasant.

UPD 1: thanks dr1v3 for the efforts of
UPD 2: ajaxtelamonidshared a link to the translation of documentation of the 5th version

Also popular now: