
Choose Yii2 or laravel
Introduction
I already wrote a similar article, but it was very incomplete and not equipped with examples, so I decided to take a second attempt and try to solve this issue most fully!
In this article, all the intricacies of development on frameworks will not be considered, since it is not possible to put it within the framework of one article. However, you can explain in sufficient detail those nuances that will help in choosing to study or implement a specific project. Compare will be Yii2 and Laravel. I understand that this is a rather holistic topic, the result of which usually says that everyone is good in their own way. I, as a person who worked with both, will try to explain my approach to choosing a framework, and I will try to show their minuses and pluses most objectively.
I’ll immediately warn you about why we are not considering Symfony.
The fact is that Symfony is a lower-level framework, which is often taken as the basis for large projects, for example, such as writing your own development framework. In principle, it cannot be compared with Laravel and Yii2, since they use its components in their implementations. Symfony is a very powerful product that allows you to flexibly customize almost any system to your needs, but there is little that can be used as turnkey solutions for small typical tasks. On GitHub you can find many libraries or extensions written for the same Yii2 or Laravel just in Symfony.
Yii2
Let's start with Yii2, as this is my first framework that I studied. I must say that this framework is studied very easily, with minimal knowledge of OOP.
pros
- Easy to learn, low start up
- Has many built-in interface solutions
- Great generator of models, controllers & CRUD
Minuses
- Not very flexible route generation
- Poor development (release of new versions)
- Too bonded libraries for frontend with backend
Now I will tell about each in more detail. The last of the minuses in general seems incomprehensible to me at first glance, but I don’t know how to put it another way, I will explain in detail below what I meant.
Easy to learn . The framework is really easy to learn, and after sitting for two days on a small project, you already begin to calmly code on it. To start studying, not enough good literature in Russian, but this is well compensated for by a good reference in English. As a last resort Google translator. Now I will be glad, it was so before. Most recently, they updated their site with guides and documentation, and now there are guides in Russian, they are here. Information on the API has not yet been translated, but there is nothing complicated. Even with a little knowledge of technical English, everything is quite simple, because it simply describes the methods that they accept, give and what they generally do, the information is here .
Embedded solutions for interfaces can be described with a whole small book, but I will try briefly. Bootstrap is built into the system, unfortunately for the third time, and a bunch of its own modules that are associated with it.
You can even have poor command of the bootstrap layout, and with the help of the built-in Yii2 methods, make pop-up modal dialogs, windows, drop-down lists, spoilers, etc.
Here is a small example that can be found on a whole bunch of sites, and even in the official Yii2 documentation:
Modal window example
use yii\bootstrap\Modal;
Modal::begin([
'header' => 'Hello world
',
'toggleButton' => ['label' => 'click me'],
'footer' => 'Низ окна',
]);
echo 'Say hello...';
Modal::end();
This example just creates a modal window with the title
Hello world
, click me button, which opens this dilogue, with the body "Say hello ..." and the footer "Bottom of the window."No need to write all sorts of 'data-target = "# id-modal"' or the like, the system will arrange all this by itself. Such things in Yii2 are called widgets that any programmer can do at all, and drag any frontend to their backend side. But this is actually a minus, the last of which I spoke above. Why is it a minus we will analyze a little later, while on the convenience of all this.
Any such widget can be called as a regular class with a static method, take parameters on which something will depend on the widget and close. There are still ways to implement widgets that do not need to be opened and closed, they will do it themselves, they only need to pass parameters on which something will depend, I will give an example from a third-party library
Third-Party Widget Example
// Multiple select without model
echo Select2::widget([
'name' => 'state_2',
'value' => '',
'data' => $data,
'options' => ['multiple' => true, 'placeholder' => 'Select states ...']
]);
This is an example from a library that allows you to call the Select2 widget in kartik-v widgets, a link to GitHub .
Here is a widget that connects all scripts, marks input and select, and processes them with the Select2 library .
In general, with the help of such solutions that someone has already written, or you can write yourself, you can add views right away with the interface and this allows you to develop very quickly.
The generator of models, controllers and representations is a separate thing, but partially connected with the previous one. In Yii2, there is a certain GUI area for selecting various generations. Please note that for other frames, if there are generators, then, as a rule, only console ones. There is an interface here and it’s very convenient to use, this charm is called gii.
Here's what it looks like:

The picture shows what she can. Model generator and CRUD are the most common things in it. Models are generated not like in laravel, the interface indicates the table, name and location of the class for the model, taking into account the namespace, the program itself pulls up all the dependencies (you can disable it if you do not need it) if the foreign key is placed and rolls out the model, with all the properties taken in the columns of the table and methods for linking with others, if any.
Frankly, I have not seen such a generator anywhere else.
CRUDgenerates ready-made interfaces, controllers for them, for data management in the specified model. Those. First you need to create a model, and then do CRUD generation. At the output, you will get a ready-made interface with a specific address where you can create new table entries, edit and delete them.
It is very convenient to use to create admin panels or some dashboards. A ready-made interface is quickly generated, which can then be edited and used by assigning protection to the routes by authorization or otherwise. The interface itself uses many built-in widgets for this, which can also be reconfigured as you wish. This is really fast development of systems with data management interfaces. You can quickly make an efficient CMS for the needs of a specific project. My opinion is that this is the most important plus of Yii2 in comparison with other frameworks.
Now let's talk about the cons. About them short enough so as not to inflate the article to unprecedented proportions.
Not very flexible route generation. In class controllers for Yii, routes are specified as follows:
An example of creating a route in the controller
/*----*/
/**
* Your Annotation
* @return mixed
*/
public function actionIndex()
{
return $this->render('index', []);
}
/*----*/
Any path in the controller must begin with the word action and its address, for example, Index , is indicated with a capital letter . If you write in two words, for example actionArticlesList , then the path will be as follows: / controller_name / articles-list . If we need to somehow organize the formation of routes, there are two ways:
- Set rules in the config
- Write your class for a specific group of routes, and specify it in the config.
I will not dwell on the config in detail, but it looks something like this:
[
/*---*/
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'//' => '//',
'///' => '//',
],
],
/*---*/
]
The rules , precisely specified rules. There you can specify your class, or come up with your own expression for the route, you can read more about this in the official documentation .
The second point of the minuses , I think it’s especially not worth explaining. It should be noted that Yii2 still uses bootstrap-3, and quite a few have been added recently.
Well, the last point that I promised to clarify is the too much glued frontend with the backend. As I wrote above, many widgets and other solutions immediately make the generation of ready-made solutions in views. This is good and fast, but many of them throw scripts directly into the body of the page, php and html are mixed in the code of these widgets, which doesn’t look very good and it’s quite problematic to maintain such code.
This development method does not allow the use of collectors such as WebPack, Gulp or others. You can use it more precisely, but you will have to abandon the main advantage of Yii2 - not to use generators and ready-made solutions for the interface. Do not use classes that allow you to collect scripts and css in assets and the like.
In modern development, everything is going to separate the frontend from the backend as far as possible, and in this regard, Yii2 becomes obsolete. I hope this minus is clear enough.
Laravel
Since we got acquainted with Yii2 in sufficient detail, here you can give the pros and cons for comparison with the previous Yii2 framework
pros
- Has built-in script and scss collector
- Built-in Blade Template Engine
- Very flexible Routing Formation
- Very flexible REST API writing capabilities
- Developing fast
Minuses
- Great functionality works through facades and IDE systems do not see methods and properties in some classes, showing warnings
- Studied a little harder Yii2
- No official documentation in Russian
- No built-in interface generators
The built-in collector is based on WebPack, in fact it is an add-on on it, which makes it easy to get started, and collect the frontend without delving into the fat WebPack manuals and how to configure it.
In the system, it is called laravel mix , and this is essentially WebPack, already configured for most tasks, where we simply indicate where we get the source from and where we put the result.
Mix example
let mix = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
In the example, the standard configuration that appears immediately after installing the framework. You can create as many mixes as you like if you have a separation of several frontend applications.
In the example, the standard configuration that appears immediately after installing the framework. You can create as many mixes as you like if you have a separation of several frontend applications.
The mix immediately knows how to assemble scss, single-file components of Vue, as well as in new versions of Laravel, Vue.js comes immediately to the supply of the framework.
Template Blade, than it closely resembles Twig, but the syntax and principle of operation is slightly different. I don’t know which one is better, but I have not yet encountered such tasks that can be implemented on Twig and cannot be implemented on Blade. The only minus of Blade, which I see so far, is that Twig is known to many, and Blade is only for Laravel developers.
Very flexible route generation . The mechanism is very similar to the symfony, but instead of annotations, use a separate file and the facade class Route , with a set of static methods.
The advantage compared to Yii2 is that in the controllers the methods can be called whatever you like, and the routes themselves too. We write them in a separate directory, and indicate the current route, what type of request it is (POST, GET, etc.), and indicate which controller it is and the method in the controller. You can also specify a name to display a link through it through the Blade template engine.
Route Assignment Example
/*---*/
Route::get('/dashboard/newsList', 'DashboardController@newsList')->name('dashboard/newsList'); //Запрос GET, его адрес, вторым параметром указывает на контроллер и метод
Route::middleware('auth')->delete('/dashboard/newsList/news/{uuid}', 'APINewsController@DeleteNews'); //Запрос DELETE, требующий авторизации, передающий последним параметром в URL uuid, И направленный на соответствующий контроллер и метод.
/*---*/
In routing, it is convenient to use middleware, which before sending a request for processing the controller I can check some data and depending on it send it to the controller for processing or not. One of these checks may be user authorization in the system. Moreover, middleware itself can be used both in the controller and when declaring a route in routes .
The system is very flexible. You can assign different handlers of the same controller to one route, depending on the method of transmitting the HTTP request.
I did not mention this in Yii2, but there is also a request management system there, but like all other routes, it is configured either through its own class or through the config, which is not always convenient. Yii2 has yii \ rest \ ActiveController- which allows you to quickly configure the REST FULL API, but it is also not as flexible as we would like.
Thanks to such a system of routes, I would choose Laravel to build a project running on the REST API. Thus, at this point, I answered the next plus, “Very flexible REST API writing capabilities,”
Laravel is developing very fast . New versions are constantly coming out that correct the mistakes and shortcomings of the previous ones, quickly increasing the efficiency of the framework. He is probably the fastest growing framework that I know.
We pass to minuses.
Work through the facades,most of the extensive Laravel classes. Such a difficult proposal, I will explain! The fact is that many classes of the framework use the dynamic creation of properties and methods, depending on some conditions.
It’s easier to give an example. We declare a database model class, which is an extension of the standard Illuminate \ Database \ Eloquent \ Model class , in which there are no static methods where, select, etc., but in fact they are and you can use them. These are miracles. The fact is that such methods are formed from the so-called facades, which read the usual class methods and turn them into static ones. And properties are obtained by accessing the database. Of course, it’s convenient that you can work with the same properties both statically and dynamically, but in this way, it turns out that the IDE does not see these methods and displays a warning about calling non-existent methods. True, there is already a solution to this problem - use the IDE-helper, which solves the problem. I give a link to GitHub . On GitHub, it’s pretty detailed how to work and install it.
Paragraph "We study a bit complicated Yii2»can not be considered objective, as this is my personal opinion. It was quite difficult for me to switch from Symfony and Yii2 to this magic with facades. However, if you think carefully, I sat a couple of days over the guides and manuals, too, began to slowly write on it, improving my knowledge and skills.
It seems to me that if I started to study Laravel first and then Yii2, I would say that Yii2 was harder to study, so everyone’s business is subjective here. In any case, studying them is quite simple both.
No documentation in Russian . Yes, this is sad, not so bad. Most developers speak at least technical English, and the official documentation is provided with good examples, almost for any occasion. In addition, there are third-party sites, I will provide links at the end of the article.
There are no built-in interface generators . Yes, this is a big minus compared to Yii2, but also a plus at the same time. It will not work quickly, by pressing the three buttons to make a ready-made interface for working with data, but it is easy to separate the frontend from the backend and collect the frontend, as is now customary in modern development.
Generators in Laravel are generally far from Yii2, but they can still do something. There are console command generators that provide a ready-made framework for working with the console, model generators, controllers, and others. But unlike the Yii2 generators, they are empty. Those. If we generate a model, it will be empty. It is necessary to indicate for yourself which field will be the primary key, to which table it refers, which ones have links, etc. Some say that this adds flexibility, but in Yii2 you can also remove the standard generation and write your own. I do not think this is a topic of debate. Here Yii2 is definitely a winner.
Conclusion
So, we got to the main question of this article “Which framework to choose?” . As you can see from this massive description of the main differences - both frameworks are good and really good in their own way.
We can use Yii2 in cases where there are no particularly large requirements for the frontend admin panel, and the project needs to be done beautifully and in a short time.
Laravel - when we have special requirements for the front-end and a little more time for developing interfaces. And also, if necessary, a complete separation of the frontend from the backend.
Which framework to study first, you choose, on this occasion, I wrote my opinion. I hope such detailed information will allow you to make the right choice! I wish you all good luck in developing and interesting projects!
References
Официальный сайт Symfony
Официальный сайт Yii2
Официальный сайт Laravel
Ссылки из статьи:
Yii Select2 от kartik-v.
Официальный сайт Select2.
Гайды на русском языке для Yii2 (официальная документация)
API Yii2 (официальная документация)
То что обещал дать в тексте статьи:
IDE-helper для Laravel (GitHub)
Русскоязычная документация Laravel с примерами (не официальная, но хорошая)