📜 ⬆️ ⬇️

What's new in Laravel 5?



A few months ago in the studio where I work, it was decided to move the whole team to Laravel. The last couple of years, the popularity of this framework has grown tirelessly, and, as it turned out, not in vain!

I do not consider myself a guru in php and frameworks. Before that, I worked with the first and second zend a couple of times, the immortal bitrix, I came across Yii and Symfony, I invented bicycles myself, but every time I had a vague feeling of dissatisfaction.
')
For example, the Zend Framework has always made me want to quickly complete a task and forget about it as a terrible dream. Proponents of this framework certainly will not agree with me, and I do not in any way want to criticize their choice. To each his own. My Zend Framework has always caused the feeling that the code was not written by people or for people.

It always seemed to me that the same tasks could be solved more simply and elegantly. I wanted to find a framework in which I would like to write. Which I could learn in my own fingers and do what I like to do - programming, creating something new. I think every carpenter has a favorite hammer, and such a desire for a programmer is quite natural. Who among us, those who write in php, did not look with envy at Rails in Ruby or Django in Python?

The last straw was the post from JetBrains about the extended support in the new version of PhpStorm 8 templates Blade and Source & Test directories. In this IDE, we created the first project on Laravel.

After working with Laravel, I realized that I had found what I was looking for. Perhaps that is why the slogan “You have arrived” has become the symbol of Laravel.

From the first day he never ceases to surprise me pleasantly, from the documentation, the community (when I ran into a problem while writing this article, I went to the online chat community, described the problem and answered me personally (!) Taylor Otwell, the creator of the framework) and tutorials, to various buns that can and should be used after placing the project on the server.

But my article is not about that. About the pros Laravel written already enough.

In this article I would like to write about the new version of Laravel, the official release of which will take place in November, but you can download and try it now through Composer.

Initially, the version was supposed to be called 4.3, but the new directory structure and some significant changes in the code prompted the creators to decide to announce version 5.0.

How serious were these changes judging you. So let's actually figure out what we are preparing Laravel 5.

Installation


Installing a new version is essentially the same as the old one. To get started, download Laravel 5 by adding a line to the file composer.json

"require": { //... "laravel/framework": "5.0.*@dev" //... } 


After that, run composer update, and at the end of the operation you will have the latest version installed.



Structure


If you look at the structure of Laravel 4 and Laravel 5, then you can immediately notice the difference. First of all, the Config, Tests, Storage and Database folders were moved from the App folder to the root. There is a new resources directory.



A logical question arises: what is left in the App folder?

Now only the application logic is stored in the App folder. Thus, the developers legalized what most of the Laravel developers had done before — they deleted the model folder and created a separate directory for everything related to the development of this particular project - models, teams, events and the like. First of all, this allows for a clear distinction between the code of the framework itself and the code that the developer himself writes.

In the App folder, there are 3 new directories by default. The Console directory is intended for classes of console commands, the Service Providers folder contains service provider classes, the Http folder contains controllers, filters, and everything related to routing.



In turn, in the Http directory there are 3 folders - Controllers for application controllers, Filters for route filters, which are now created as separate classes, and the Requests folder, which I will discuss in detail below.
The View folder has been moved to the Resources directory, along with the Lang localization folder.
To some, the new structure may seem unusual, but by myself I can say that in a couple of days you will understand that this is much more convenient.

The first question that you will most likely have in connection with the change in structure: what happened to the namespaces and autoloading of classes?

Namespaces

To my great joy, Laravel 5 officially uses the psr-4 standard, which means every class in the App folder that has the correct namespace will be available to the autoloader.
So just make sure that every class in this folder starts with the App \ * directory name and forget about problems with downloading files forever.

On the other hand, using psr-4 means that access to the facades now requires access from the global namespace, for example, \ Auth :: * method name * or \ Events :: * method name *.
In this regard, the facades now need to import the command use \ name of the facade (for example \ View) at the beginning of the file or access them through a backslash.

In addition, it is now necessary to specify the namespace for the controllers. Therefore, make sure that each of your controllers contains a string
 namespace App\Http\Controllers; 

and uses the abstract controller namespace
 use Illuminate\Routing\Controller; 


If you use BaseController as the parent class of all your controllers, then you can put the last line there, so all your controllers will have access to this namespace.

Application Root
What if you don't want to access the main folder of your application as an App? What if you used to call the directory in which the application logic is stored, by the name of the application itself, as many did in Laravel 4?

The developers have foreseen this. You just need to write $ php artisan app: name and the desired name of your application on the command line. Laravel will independently change the namespaces in the required files, as well as the settings in the configuration files.

If you want to use a nested directory, use two backslashes, like so
 $ php artisan app:name MyAppName\\HabrProject 


By the way, a new file namespaces.php has appeared in the Config folder, in which the namespace for the application as a whole and the file paths are written. Useful if there are problems with autoloading!

Introduction of method parameters

Another powerful innovation of Laravel 5 was the introduction of method parameters (Method Parameter Injection or just Method Injection).
Previously, if we needed some kind of model class in the controller, for example, a repository, we could use Ioc Container Dependency Injection, that is, transfer the class name to the controller's constructor and assign it to an object property.
The ioc container independently created an instance of this class and returned it to the controller property through which we accessed it. And it was awesome.

For example:

  class FeedController extends BaseController { protected $feedbackRepository; /** * @param FeedbackRepository $feedbackRepository */ public function __construct(FeedbackRepository $feedbackRepository) { $this->feedbackRepository = $feedbackRepository; } public function index($id) { $feed = $this->feedbackRepository->getFeed($id); return View::make('feed.index', compact('feed')); } 

However, what if we only need the object in one method? Why create an instance of the object in the constructor of the whole controller if it will be used only in one of its methods?
Therefore, the introduction of the method parameter appeared in Laravel 5!
Now you can specify a class in any controller method, and you will automatically get access to its methods through the Ioc container. Our example would now look like this:

  class FeedController extends BaseController { public function index(FeedbackRepository $feedRepo, $id){ $feed = $feedRepo->getFeed($id); Return view('feed.index', compact('feed') } } 

And that's it! In a magical way, Ioc container will find and connect my repository by itself.

But the real power of this innovation can be felt in conjunction with another new feature:

Requests and form requests (FormRequests)

Remember, I was talking about the Requests folder in the App \ Http directory? So we finally got to her.
Let's remember how we verified the user input when submitting a form to Laravel 4.2.

If you have worked with Laravel, then you certainly know the facade of the Validator.
It provides powerful functionality for validating data received from the user. However, each developer used it differently. Someone used a validator right in the controller,
someone wrote the validation rules in the model (an array of rules []) and used the isValid method.

Now you can forget about this: Laravel provides a separate level of abstraction for processing requests to the form.
Let's see how this works.
At the command prompt, type php artisan make: request MyRequest and the framework will generate a request template for the form for you.

In this class, which inherits the FormRequest class, there are only 2 methods: authorize and rules.
Rules returns an array in which you can write validation rules for your form, just like in Laravel 4.
The authorize method returns false by default.
If we now try to submit a form associated with this class, we will get an forbidden page in the browser.

So, the authorize method checks whether the user accessing the form has the right to send it. For example, does the user have the right to edit an article that he did not write? Post a comment if it is not logged in? This is exactly the place where checks now need to be placed.

Suppose we have a form that publishes a status on a user's wall. We want the status field (normal input type = 'text' name = 'status') to be mandatory and contain, say, 20 characters. We also need to check that the user publishes the status on his wall, that is, the user’s page id is the same as the post author.
In this example, our validator class would look like this.

 namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use \Auth; class AddFeedRequest extends FormRequest { public function rules() { return [ 'status' => 'required|min:20', ]; } public function authorize() { return Auth::id() == $this->route->parameter('id'); } 

Now, using the method parameter implementation, which we talked about above, we simply need to specify the class name in the parameters of the controller method responsible for submitting the form.
If we use a REST controller, this will be the store method.

  public function store(MyRequest $request) { //   } 

And that's it! Nothing more needs to be done! Laravel itself validates the form and executes the code contained in the controller method if the validation succeeds. Once again: not a single line of code from the store method will be executed if the form does not pass validation. In my opinion, this is insanely cool!

Generators

If we type php artisan on the command line, we will see a whole new section called make:
We have already used one of them to generate the class myRequest. In addition, the make command: helps you create a controller, a console command,
filter, migration, service provider.

I especially want to highlight the php artisan make: auth. This generator will do for you what you have done over and over in each new project - the user authorization system.

If we execute it now, we will see that Laravel will create for us two controllers - one responsible for authorization, the second for password recovery, password resets migration, 2 validator classes for login and register requests. Only one team and a template for authorization is ready!

Route caching

The routes command has also grown into a whole section. Now to see the list of routes you need to enter php artisan route: list.
It’s also hard to miss the new route: cache command. It does a very simple thing - caches your routes.
If you run this command, you will see that the file routes.php appears in the storage / meta folder. It contains a cache of your routes. Now Laravel will first access it, and not the main http / routes.php file.

When developing this, it is hardly useful, at least it is difficult for me to imagine such a situation, but with a delay when the project is already written and new routes are rarely added, this can be very useful.

Contracts

All components of Laravel 5 now implement a particular interface from the illuminate / contracts. Thus, the developers tried to make your application more flexible and less dependent on Laravel itself.

Laravel 4 often had problems with type-hinting interfaces. If you specified in the method parameters an object instance that should implement an interface, the Ioc container considered it as dependency injection and tried to create an instance of the class, which led to errors.

To solve this problem, it was necessary to directly associate the interface with a specific interface implementation class using app :: bind. However, it still caused some problems, for example during unit-testing.
In Laravel 5, it is enough to use the interface at the beginning of the file using use (for example, use Illuminate \ Contracts \ Mailer) and type-hinting will work as it should.

This allows you to write more flexible applications without being tied to specific classes-implementations.

What if in the future you want to connect another authorization module that is different from the standard Laravel module? Another caching module? Sending letters? Just make sure that it implements the interface from the contracts folder and write the code based on the type-hinting interfaces.

New features helpers

A trifle that you will use again and again in your projects: the connection of the view files is now available through the view function ('viewname'). The old way View :: make also works, but now, as I said above, you need to access it via a backslash.

The same fate befell Redirect :: to - now you can simply write redirect ('route').

Among other changes in the usual tools of work, it is worth mentioning that the HTML and Form facades are no longer included in the standard Laravel package. Do not worry, if you are used to them, you can easily connect them through the composer.

Socialite

Laravel 5 has its own Socialite Beta module, which is designed to authenticate third-party services such as Twitter, Facebook, GitHub. We had to write quite often plug-ins for authorization for various social networks and how it would be great if there were similar tools in other frameworks. The plugin is optional and to add it you just need to connect the dependency. Judge for yourself, you just need to create the provider config and after that all the necessary methods will be available in the form:

 $this->socialite->driver('twitter')->user(); 

All you need to do is connect the appropriate class at the beginning of your file:
use Laravel \ Socialite \ Contracts \ Factory as SocialiteFactory;
In the near future we plan to add authorization for vk.

Blade

Of the changes in Blade, there is one significant reason why the community has created dozens of similar questions over the past couple of days. Now both the {{link_to_route ('login_path')}} tag and the {{{link_to_route ('login_path')}}} tag will be screened and displayed as text to reduce the risk of code injection.

Instead, you have to use the construct
  {!! link_to_route('login_path') !!} 

By the way, to facilitate the transition to the new version of Blade, you can replace the tags with the old ones:
Blade :: setRawTags ($ openTag, $ closeTag);
Then do not have to rewrite all views.



Summary


The fifth version is exactly the version that you should now begin your acquaintance with Laravel, if you still postpone this exciting moment. The vast majority of plug-ins already support the new version of the framework, and comprehensive documentation will be ready for release. Laravel in my opinion is the most interesting and promising project in the php community lately. It's nice to see how every day he attracts more and more supporters.

If you want to know more about Laravel, here are some useful resources:

• laravel.com
• laravel.io
• laracasts.com

Maybe I missed something, then write in a personal, I will correct. Thanks for attention! I hope the article was helpful.

Source: https://habr.com/ru/post/238017/


All Articles