PHP
Article

7 Reasons to Choose the Yii 2 Framework

By Matthew Beaumont

Late last year, SitePoint published an article highlighting the top PHP frameworks. Tied for the number four spot was the Yii (pronounced Yee) Framework. At that time the latest version of the framework available was 1.1.14. Recently, Yii 2.0 was made available, so you can begin to use it in production.

While we did cover it recently when it was still in RC status, it just reached full release status, and we feel like it’s time to revisit the topic with some reasons for choosing it over alternatives.

1. Easy to Install

For web developers, time is money, and no one wants to spend their precious time on a complicated installation and configuration process.

Installation is handled using Composer. If you want a description of the installation process, Sitepoint recently published a great article here. I tend to favor using the basic application template, even when my site has a separate front- and backend component. Instead, I opt to use a Module for the backend portion of my sites. (Yii Modules are best described as mini-applications which reside inside your main application).

Note: Many of the directory references in later examples use the directory structure from the simple template.

2. Utilizes Modern Technologies

Yii is a pure OOP framework, and takes advantage of some of PHP’s more advanced features, including late static binding, SPL classes and interfaces, and anonymous functions.

All classes are namespaced, which allows you to take advantage of their PSR-4 compliant autoloader. That means that including Yii’s HTML helper class is as simple as:

use yii\helpers\Html;

Yii also allows you to define aliases to help simplify your namespaces. In the above example, that use statement will load a class definition which is located by default in the directory /vendor/yiisoft/yii2/helpers. This alias is defined in the BaseYii class on line 79:

public static $aliases = ['@yii' => __DIR__];

The framework itself is installed using Composer, as are its extensions. Even the process of publishing extensions is as easy as creating your own composer.json, hosting your code at Github, and listing your extension on Packagist.

3. Highly Extensible

Yii is like a suit that looks great off of the rack, but is also very easy to tailor to fit your needs. Virtually every component of the framework is extensible. A simple example is the addition of a unique body ID to your views. (In case you’re interested in knowing why you might want to do this, take a look at this article).

First, I would create a file in my app\components directory with the name View.php, and add the following:

namespace app\components;

class View extends yii\web\View {

    public $bodyId;

    /* Yii allows you to add magic getter methods by prefacing method names with "get" */

    public function getBodyIdAttribute() {
        return ($this->bodyId != '') ? 'id="' . $this->bodyId . '"' : '';
    }

}

Then, in my main layout file (app\views\layouts\main.php), I would add the following to the body tag of my HTML:

<body <?=$this->BodyIdAttribute?>>

And finally, I would add the following to my main configuration file to let Yii know to use my extended View class instead of its own default:

return [
    // ...
    'components' => [
        // ...
        'view' => [
            'class' => 'app\components\View'
        ]   
    ]
];

4. Encourages Testing

Yii is tightly integrated with Codeception. Codeception is a great PHP testing framework that helps simplify the process of creating unit, functional and acceptance tests for your application. Because you ARE writing automated tests for all your applications, right?

The Codeception extension makes it simple to configure your application during testing. Simply edit the provided /tests/_config.php file to configure your test application. For example:

return [
    'components' => [
        'mail' => [
            'useFileTransport' => true,
        ],
        'urlManager' => [
            'showScriptName' => true,
        ],
        'db' => [
                'dsn' => 'mysql:host=localhost;dbname=mysqldb_test',
        ],
    ],
];

Using this configuration, the following would happen:

  1. Any emails sent during your functional and acceptance tests would be written to a file instead of being sent.
  2. The URLs in your tests would take on the format index.php/controller/action rather than /controller/action
  3. Your tests would use your test database, rather than your production database.

A special module for the Yii Framework also exists within Codeception. It adds several methods to the TestGuy class, which help you work with Active Record (Yii’s ORM) during functional tests. For instance, if you wanted to see if your registration form successfully created a new User with the username “testuser”, you could do the following:

$I->amOnPage('register');
$I->fillField('username', 'testuser');
$I->fillField('password', 'qwerty');
$I->click('Register');
$I->seeRecord('app\models\User', array('name' => 'testuser'));

5. Simplifies Security

Security is a crucial part of any web application, and fortunately Yii has some great features to help ease your mind.

Yii comes with a Security application component that exposes several methods to help assist in creating a more secure application. Some of the more useful methods are:

  • generatePasswordHash: Generates a secure hash from a password and a random salt. This method makes a random salt for you, and then creates a hash from the supplied string using PHP’s crypt function.
  • validatePassword: This is the companion function to generatePasswordHash, and allows you to check whether the user supplied password matches your stored hash.
  • generateRandomKey: Allows you to create a random string of any length

Yii automatically checks for a valid CSRF token on all unsafe HTTP request methods (PUT, POST, DELETE), and will generate and output a token when you use the ActiveForm::begin() method to create your opening form tag. This feature can be disabled by editing your main configuration file to include the following:

return [
        'components' => [
            'request' => [
                'enableCsrfValidation' => false,
            ]
    ];

In order to protect against XSS, Yii provides another helper class called HtmlPurifier. This class has a single static method named process, and will filter your output using the popular filter library of the same name.

Yii also includes ready-to-use classes for user authentication and authorization. Authorization is broken into two types: ACF (Access Control Filters) and RBAC (Role-Based Access Control).

The simpler of the two is ACF, and is implemented by adding the following to the behaviors method of your controller:

use yii\filters\AccessControl;

class DefaultController extends Controller {
    // ...
    public function behaviors() {
        return [
            // ...
            'class' => AccessControl::className(),
            'only' => ['create', 'login', 'view'],
                'rules' => [
                [
                    'allow' => true,
                    'actions' => ['login', 'view'],
                    'roles' => ['?']
                ],
                [
                    'allow' => true,
                    'actions' => ['create'],
                    'roles' => ['@']
                ]
            ]
        ];
    }
    // ...
}

The preceding code tells DefaultControllerto allow guest users to access the login and view actions, but not the create action. (? is an alias for anonymous users, and @ refers to authenticated users).

RBAC is a more powerful method of specifying which users can perform specific actions throughout your application. It involves creating roles for your users, defining permissions for your app, and then enabling those permissions for their intended roles. You could use this method if you wanted to create a Moderator role, and allow all users assigned to this role to approve articles.

You can also define rules using RBAC, which allow you, under specific conditions, to grant access to certain aspects of your application. For instance, you could create a rule that allows users to edit their own articles, but not those created by others.

6. Shorten Development Time

Most projects involve a certain amount of repetitive tasks that no one wants to waste time with. Yii gives us a few tools to help you spend less time on those tasks, and more time customizing your application to suit your clients’ needs.

One of the most powerful of these tools is called “Gii”. Gii is a web-based code scaffolding tool, which allows you to quickly create code templates for:

  • Models
  • Controllers
  • Forms
  • Modules
  • Extensions
  • CRUD controller actions and views

Gii is highly configurable. You can set it to only load in certain environments. Simply edit your web configuration file as follows:

if (YII_ENV_DEV) {
    // ...
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['127.0.0.1', '::1']
    ]
}

This ensures that Gii will only load when the Yii environment variable is set to development, and that it will only load when accessed via localhost.

Now let’s take a look at the model generator:

Gii Model Generator

The table name uses a typeahead widget to try to guess which table your model is associated with, and all fields have a rollover tooltip to remind you how to fill them out. You can preview code before you ask Gii to generate it, and all the code templates are completely customizable.

There are also several command-line tools available to help create code templates for database migrations, message translations (I18N) and database fixtures for your automated tests. For instance, you can create a new database migration file with this command:

yii migrate/create create_user_table

This will create a new migration template in {appdir}/migrations that looks something like this:

<?php

    use yii\db\Schema;

    class m140924_153425_create_user_table extends \yii\db\Migration
    {
        public function up()
        {

        }

        public function down()
        {
            echo "m140924_153425_create_user_table cannot be reverted.\n";

            return false;
        }
}

So let’s say I wanted to add a few columns to this table. I would simply add the following to the up method:

public function up()
{
    $this->createTable('user', [
        'id' => Schema::TYPE_PK,
        'username' => Schema::TYPE_STRING . ' NOT NULL',
        'password_hash' => Schema:: TYPE_STRING . ' NOT NULL'
    ], null);
}

And then to make sure I can reverse the migration, I would edit the down method:

public function down()
{
    $this->dropTable('user');
}

Creating the table would simply involve running a command on the command line:

./yii migrate

and to remove the table:

./yii migrate/down

7. Easy to Tune for Better Performance

Everybody knows that a slow website creates disgruntled users, so Yii provides you with several tools to help you squeeze more speed out of your application.

All Yii’s cache components extend from yii/caching/Cache, which allows you to choose whichever caching system you want while using a common API. You can even register multiple cache components simultaneously. Yii currently supports database and file system caching, as well as APC, Memcache, Redis, WinCache, XCache and Zend Data Cache.

By default, if you’re using Active Record then Yii runs an extra query to determine the schema of the table(s) involved in generating your model. You can set the application to cache these schema by editing your main configuration file as follows:

return [
    // ...
    'components' => [
        // ...
        'db' => [
            // ...
            'enableSchemaCache' => true,
            'schemaCacheDuration' => 3600,
            'schemaCache' => 'cache',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
    ],
];

Finally, Yii has a command line tool to facilitate the minification of frontend assets. Simply run the following command to generate a configuration template:

./yii asset/template config.php

Then edit the configuration to specify which tools you want to you perform your minification (e.g. Closure Compiler, YUI Compressor, or UglifyJS). The generated configuration template will look like this:

<?php
    return [
        'jsCompressor' => 'java -jar compiler.jar --js {from} --js_output_file {to}',
        'cssCompressor' => 'java -jar yuicompressor.jar --type css {from} -o {to}',
        'bundles' => [
            // 'yii\web\YiiAsset',
            // 'yii\web\JqueryAsset',
        ],
        'targets' => [
            'app\config\AllAsset' => [
                'basePath' => 'path/to/web',
                'baseUrl' => '',
                'js' => 'js/all-{hash}.js',
                'css' => 'css/all-{hash}.css',
            ],
        ],
        'assetManager' => [
            'basePath' => __DIR__,
            'baseUrl' => '',
        ],
    ];

Next, run this console command in order to perform the compression.

yii asset config.php /app/assets_compressed.php

And finally, edit your web application configuration file to use the compressed assets.

'components' => [
    // ...
    'assetManager' => [
        'bundles' => require '/app/assets_compressed.php'
    ]
]

Note: You will have to download and install these external tools manually.

Conclusion

Like any good framework, Yii helps you create modern web applications quickly, and make sure they perform well. It pushes you to create secure and testable sites by doing a lot of the heavy lifting for you. You can easily use most of its features exactly as they are provided, or you can modify each one to suit your needs. I really encourage you to check it out for your next web project!

Have you tried Yii 2? Will you? Let us know!

  • http://emadghasemi.ir emadgh

    I’m sure by 1.1.14 you mean 1.1.15 :D

    Anyway,Nice article.
    Thank you

    • http://www.beaumontwebdev.com Matthew Beaumont

      Thank you so much for the feedback. I can see where that would be confusing, but what I meant is that when Bruno posted his article in 2013, we were up to 1.1.14. 1.1.15 didn’t come out until June 2015.

      • http://emadghasemi.ir emadgh

        Yes, You’re right

        Thanks

  • Husni Mansour

    most of these features already exists in Laravel 4 and laravel is getting ready to launch L5, i think Yii has felt behind now, just my opinion.

    • Joe

      Laravel 4 does not have classes generation based on database. That’s one huge plus for Yii1/2 where it gives you the ability to generate classes based on current database structure.

      • Anton

        Symfony (Read as doctrine) has been doing that for a long time…

    • decemvre

      And yet, I bet I can produce the exact same web application considerably faster in Yii2 than you can in Laravel.

      • http://www.incomepitbull.com/ Wade Shuler

        Exactly! 9 times out of 10, this is the deciding factor. Most sites developed, the person has no idea if it will take off or not. Get in, get out, for a respectable budget. If it takes off, you would be better to ditch PHP completely. No sense creating a corporate level project and taking twice as long, for the site to fall flat on it’s face.

    • Laravel is bloated and Slow

      It’s actually Laravel that became very bloated and “fell behind” in performance — you can see Laravel at the bottom of Techempower’s PHP Framework Benchmarks. Actually, Laravel is even slower than CakePHP.

      [IMG]http://i.imgur.com/mKlNKmW.png[/IMG]

      Laravel 4 is also morbidly obese, it takes up a bloated [b]92 MB[/b] in disk in its normal composer install:

      Laravel is also a memory hog, and L4 consumes twice the memory as the previous version, and it is twice slower even after otpimization. Here are some performance results posted in the [url=”http://forumsarchive.laravel.io/viewtopic.php?id=8175&p=3″]Laravel Forums[/url]:

      [b]Laravel 4[/b]

      [code]Requests per second: 21.35 [#/sec] (mean)

      Time per request: 468.311 [ms] (mean)

      Time per request: 46.831 [ms] (mean, across all concurrent requests)

      Transfer rate: 10.96 [Kbytes/sec] received[/code]

      [b]Yii 1.1.13[/b]

      [code]Requests per second: 277.74 [#/sec] (mean)

      Time per request: 36.004 [ms] (mean)

      Time per request: 3.600 [ms] (mean, across all concurrent requests)

      Transfer rate: 63.47 [Kbytes/sec] received[/code]

      [b]CakePHP 2.3.5[/b]

      [code]Requests per second: 129.45 [#/sec] (mean)

      Time per request: 77.252 [ms] (mean)

      Time per request: 7.725 [ms] (mean, across all concurrent requests)

      Transfer rate: 29.20 [Kbytes/sec] received[/code]

      As the Laravel user that produced the above tests put it in the Laravel Forums, “I fell in love with L4, but it seems its performance is not ready for production.”

    • DanBangWTFRajib

      well you just opened the can of worms with the flame war……

      Yii is not just framework, its different sustainable ecosystem. If you pay closer attention to the number of extensions Yii have then I can say Yii is PHP’s reply to Python/Django about how fast and efficiently web application could be built on top of extensions/modules provided by other developers.

      Yes, Symfony also has bundle system and I love Symfony too… If there’s something similar in Laravel then please educate me (I am seriously not aware of it).

    • http://harikt.com/ Hari K T

      Not against Laravel, but I would like to clarify version numbers don’t count to make any framework as bad or not.

  • Vitor Silva

    Nice article, kudos to you. Worth while the wait for Yii 2 release. I would love to read more yii articles on sitepoint

    • http://www.beaumontwebdev.com Matthew Beaumont

      I’m glad you enjoyed it. We are definitely planning to write more articles about Yii. Is there anything in particular you’d like to see covered?

      • Vitor Silva

        Very happy to know there you are planning some more articles, I am going to keep an eye on them.
        Once people will tend to migrate from v1.1* to v2, I believe a steping stone article would be helping people to make that transition. Showing how to make both versions initially coexhist and gradully refactor the code to 2.0 some sort of cookbook, guide, howto or possible approaches. What is you you thought about that ?

        • http://www.beaumontwebdev.com Matthew Beaumont

          Hi Vitor. I will start by quoting the new guide: “There are many differences between versions 1.1 and 2.0 of Yii as the framework was completely rewritten for 2.0. As a result, upgrading from version 1.1 is not as trivial as upgrading between minor versions.”

          So personally I would not try to get the two working together. @Bruno Skvorc wrote a great article on legacy code that you can find here: http://www.sitepoint.com/legacy-code-cancer/.

          Instead, I would choose to maintain my 1.1.x app (Yii will continue to support 1.1 through December 31st, 2015), and develop a new version in parallel using 2.0. Of course I realize that this may not be feasible for everyone, so you might want to check out the following link:

          http://www.yiiframework.com/doc-2.0/guide-tutorial-yii-integration.html

          Perhaps I’ll play with this in the future though and see if I can come up with some helpful tips.

      • http://harikt.com/ Hari K T

        Hey @matthew_beaumont:disqus,

        I love to see something.. Mostly active record has been blamed for violating SRP , and testing is hard without touching the db. So how is testing made will be nice to hear.

        Thanks!

        • http://www.beaumontwebdev.com Matthew Beaumont

          I can definitely look into writing an article on testing. You can test your ActiveRecord objects using the DB if you use Fixtures, but if you don’t want to use the DB, you can create Mock Objects.

          • http://harikt.com/ Hari K T

            Thank you @matthew_beaumont:disqus .

      • Nazim

        My request is for api integration lesson……

  • Chris O’Connell

    While those seven reason are all very good reasons, they don’t really distinguish Yii from any other modern framework. Both Zend Framework 2 and Symfony 2 have the exact same list of reasons to use them (I’m sure some of the other top frameworks do as well, I’m just not familiar with them).

    I’d be interested in hearing very specific area’s that Yii excels at where other frameworks are weaker in.

    • Bill Keck

      Laravel is a resource hog, built on top of Symfony, and Symfony and Zend are overly complicated in the all the wrong ways, in my opinion. Thta said, they’re all solid frameworks.

      Yii’s AR is built-in, not relying on Doctrine, so it is more seemlessly integrated, and in my opinion, more intuitive. No need for yaml, no need to specify every route through the site, no need to use twig or smarty, and it comes with integrated bootstrap 3 widgets, right out of the box. Yii 2 also provides an advanced template, with front-end and back-end, with working user model and password recovery, making it easier to get up and running quickly. Yii 2’s event and behaviors architecture is feature-rich and intuititive. Yii 2 flows beautifully.

      Ultimately, for a capable programmer, it’s a matter of personal preference, which style you feel connected to… Persoanlly I prefer Yii 2 far and above the other frameworks, while still respecting the other frameworks.

      • http://harikt.com/ Hari K T

        Your arguments are nice…

        But :-)

        Components stands different. The era is about plug and play … So if you don’t like doctrine you can choose something like idiorm, paris, propel, phpactive record , aura.sql etc.

        That said I am not sure whether yii will split their components for the php community to make use of it via composer.

        The era is about composer and packagist. Good components , standalone nice… Frameworks are not bad, it is also nice if you can build it from components :) .

        My thoughts, and people may have different opinion.

        • DanBangWTFRajib

          You can plug and play in Yii with extensions…

          If you want to use Doctrine instead of AR ORM, then no problem, plug and play and there is extension for it as well… In spite of the ORM code reside there, yii lazy loading will never tough ORM when you use Doctrine…. Major performance boost :D

          I have been through the codebase of Yii and yes it has somehow tight integration (or loosely coupled whatever its said) between its base and the component , but it represents the DRY concept pretty neatly (much like RoR). Two components are hardly coupled with each other.

          On the other hand, every project is different architecture, Yii put this all together for us for rapid development with vast performance improvement. Standalone packages are nice, but if you look at the code base then much of Yii components can be ported to standalone package with very less effort, but it may kill the DRY concept for decoupling one. The argument is still on water which is better either DRY or Decoupled.

          • Guest

            delete testing

          • http://harikt.com/ Hari K T

            For the record : I was not mentioning how you can use doctrine in Yii :-) .

      • Abhinandan

        Zend => “Enterprise”
        Laravel => better syntax, better community
        Symfony => mature, better support
        Yii => lazy loading by default

        If you are already happy with a framework, that’s cool. Don’t let these articles distract you!

        • Bill Keck

          One thing I agree with you is that you should code in the framework you are happiest with. I don’t agree that you can sum up Yii 2 as lazy loading by default. None of the ORMs for these frameworks can deliver true enterprise performance if you use their ORMs. Complex querries, with multiple joins, multiple subqueries, inside of large data sets, are not suitable for PHP ORMs. That said, you can use the PHP ORMs for trivial implementations of dropdown lists etc.

          • Abhinandan

            Nice to hear that. But that’s a feature of Yii ORM not the Yii framework itself. I don’t know whether Yii ORM is decoupled enough that I can use it in my framework of choice.

          • Bill Keck

            I don’t think it is nor would I recommend it for that purpose.

          • Paris Qian Sen

            Yii support DI and service locator, if do not like AR, you don’t have to use it.

    • Chris Tiearney

      I’d also like to add that the widgets that Yii has are incredible. Out of the box you can provide the grid widget for example with a DataProvider supplied by your Gii generated models, and have a searchable, orderable grid. Combined with the CRUD generator from Gii, your grid also has actions for said CRUD operations.

      That being said, I tried Yii 2.0 on Sunday afternoon, on the day of release. The first thing I tried were the Bootstrap 3 widgets that it provides, specifically the Carousel widget, and it didn’t work. Haven’t had time to look at why yet though as all the output seems solid, but the Carousel layout/functionality wasn’t correct.

      Been waiting for this release a long time and can’t wait to try it out on an actual project.

  • Sworoop Mahapatra

    Hoping to see Yii2 tutorials for beginners soon on sitepoint :)

  • http://harikt.com/ Hari K T

    Nice article, and congrats to all the Yii team.

    I have a feeling, that yii could have made a few components for the PHP community for the current frameworks are all building from components from 2011 onwards.

    I hope they may split the repos soon..

  • https://devedge.eu/ Peter Petermann

    I’m a bit confused about the lowercase namespaces, https://github.com/yiisoft/yii2/blob/master/docs/internals/core-code-style.md sais that yii uses PSR-2, PSR-2 includes PSR-1, PSR-1 sais that all classnames are StudlyCaps, as namespaces are part of a full qualified classname, that implicitly includes namespaces..

  • Piyush

    I’m a beginner and don’t know much about yii2 but by reading the comments i’m now inspired to explore yii2. Can someone tell me where to find good documentation ? Also waiting for more yii2 tutorials to come on sitepoint.

  • https://devedge.eu/ Peter Petermann

    this totally ignores that a namespace is part of a fully qualified classname, and classname casing is actually described in PSR-1.
    To me it feels like “the thinking behind it” is strawman arguments to enforce a personal preference avoiding a common standard.

  • Paris Qian Sen

    Can I translate your brilliant article into Chinese and put it in my GitHub repo here: yii2-chinesization/yii2-ch-cn/news for more Chinese developers who feels interest in Yii 2? I didn’t upload it yet, coz I want to make sure I get your permission first.

  • Guest

    I use YII and I love it. No doubt it is the php framework available right now. This was expected from Mr Xii as he owned PRADO previously.

  • Rasmus Schultz

    The thing I hated about Yii 1 is still true about Yii 2: it uses nested arrays and strings for everything. Look at the amount of examples you just posted that require you to configure things by designating class and property names with strings – all of this “code” is really just data, but various run-time facilities interpret it as “code” – this approach doesn’t provide any design-time support in modern IDEs, and only limited error-checking at run-time. Yii 2, like Yii 1, relies too heavily on data, state and configuration, and not enough on PHP as a language – all this run-time hocus-pocus means either writing huge, redundant unit-tests, or crossing your fingers and hoping for the best. That is the main reason I will not be using Yii 2 – it doesn’t address any of the things I was unhappy with in the first version; this upgrade seems to be mostly about catching up with new language features and community standards – I guess if you were already completely sold on Yii, this may be all you were expecting.

    • Bsienn

      Though i love Yii and its set of tools; Your point is very valid.

    • Anonymous

      Rasmus; I think you have valid points, and I have known your stance on this since a long time back in the Yii 1.1 days.

      I think this is not news to the Yii core developers, and believe they have considered it and taken a more pragmatic approach to achieve a good balance of complexity and the things you talk about. Arguably this balance is farther away from what you think is a good fit, and that’s respectable.

      I do know that they have improved IDE compatibility quite a bit in the later Yii 1.1 time and of course with Yii 2 as well. Just saying, doesn’t matter much in relation to your comments.

      I am however curious, which framework(s) do you use instead, since you don’t use Yii 2?

    • SenG

      data as code is more of language limitation than a framework limitation. In Yii 1.x (PHP 5.2), you seem to type all your code in double quotes in widget. Now, PHP 5.4 introduced anonymous methods and the framework took advantage of it, you can make use of it instead of doing it dirtily.

  • Christoffer Niska

    Nice article indeed.

    Yii is and has been my choice of framework since 2009. I’ve evaluated both Symfony 2 and Laravel 4, and while both of them are also nice frameworks, the tools, the ease of configuration, the performance and the fact Yii feels like one solid package, is why I choose to work with it over and over again.

    Yii2 was built together with the Yii community. You can go in on GitHub and read up on the discussion of almost any component in the framework and see why it ended up like it did. A big thank you goes to Qiang, the founder of Yii, and the rest of the core development team for making sense of all those feature requests and delivering us Yii2.

  • Charles Hand

    Yii2 has little or nothing in common with Yii1. Literally everything has been changed. This is not a progression from Yii 1. You’re starting from scratch and you better be prepared to spend at least as long learning Yii 2 from scratch as you did learning Yii 1 from scratch. Twice as long, in fact, because the documentation is incomplete, there are no working examples in the community, and there are conflicting solutions to ordinary coding situations in forums. Yii 2 is not ready for prime time at all. Yii has always stopped at the blog example and considered that sufficient example, but it is not. The blog example is uselessly trivial. The only way Yii 1 became usable is when people started writing guides, putting up examples, and people started posting consistent solutions on forums. That point has not come for Yii 2 yet. It’s fine for people with time to kill, but I’m on a production schedule and don’t have time to pour through the source code in order to figure out how everything works. I think there was an awful lot of fixing of things that weren’t broken.

    • SenG

      I just completed a production ready Yii2 app. I referenced the document as and when I required it, didn’t spend any dedicated time to learn it. If you know Yii 1.x, you could quickly get Yii2

  • gutterboy

    Even though not being new to PHP, I had never used a framework before. I decided it was time to get into one recently and tried out a few…… Zend first, bloated and convoluted IMO; then I tried Laravel as it was the “popular new framework” – whilst it seemed heads and tails better than Zend, I still wasn’t convinced; I then decided to give Yii 2 a go and I finally came to understand really well how MVC works and the benefits of using a framework; the way they explain things in their documentation is far better than any other frameworks docs I have read and it’s powerful whilst not being overly complex.

    Has a long learning curve (like any framework), but a lot of that would be because I’m new to PHP frameworks in general.

    • http://www.incomepitbull.com/ Wade Shuler

      Congrats on moving to frameworks. I am well aware this thread is from 2 years ago. I am curious where people are now with their framework of choice. I too got into frameworks right as Yii2 popped out. Before it, I had built my own basic clunky MVC from scratch. I also tried a few that were out there. It wasn’t until Yii2, that MVC was clear, OOP and extending, Interfaces, etc. It all made sense. Not that other frameworks don’t utilize these, it’s just they were foggy and confusing compared to Yii2. The docs have came a long way over the last 2 years. I find that I don’t spend nearly as much time re-writing code I have already done. I can pluck something out of a past project and easily throw it into a new one, and move on.

      In today’s world, if you aren’t using frameworks, then your seriously screwing yourself and making life much harder on yourself. Now there are some projects where they want it coded 100% from scratch, however, if they knew what they were doing they would consider a framework because it would cost 1/2 as much, take 1/2 the time, and be twice as secure out of the box (so long as the dev doesn’t do something stupid lol).

      • gutterboy

        Well, almost 2 years on and I’m still loving it. I’ve been building a really large project with it which has helped me learn a lot about using it; so to answer your question I am still happily plugging along with Yii 2 :)

  • http://www.petrvnenk.com/ Petr Vnenk

    I’m curious, what changes have been done to Yii 2 in this regard? As far I haven’t discovered many improvements. I don’t get why is Yii so keen on nested arrays, for example, for form validation rules, instead of solutions closer to looking like $rules->addRule(‘attribute’, Model::RULE_TYPE) as some other frameworks use. I couldn’t find many answers online.

    • SenG

      Which one looks good?

      [[‘user_id’, ‘project_id’, ‘env’, ‘build’, ‘status’], ‘required’],

      or

      $rules->addRule(‘user_id’, Model::REQUIRED) ;
      $rules->addRule(‘project_id’, Model::REQUIRED) ;
      $rules->addRule(‘env’, Model::REQUIRED) ;
      $rules->addRule(‘build’, Model::REQUIRED) ;
      $rules->addRule(‘status’, Model::REQUIRED) ;

      With nested arrays, you define business rules with less typing.

      • http://www.incomepitbull.com/ Wade Shuler

        My vote is for the 1st example. My eye lands on ‘required’, then I can easily see what all is required. The long list makes my eyes hurt.

  • A$AP Mayonnaise {cracka}

    Slim is only a router. You should build your framework around it. I call the pattern ARCD because the data layer is persistent and immutable across routes, providing default template args. everythings a singleton so if you need something you just retrieve it like `DB::getInstance()`When passing to a render method, the array is copied so that if the route chooses to pass, the data stream remains unchanged for the next route

  • Nick Weber

    seems to be a great framework to me… wins the comparison.. I’m not a techie personally, so I had to search around to hire a yii developer and found http://www.yiiforce.com Can anyone recommend them or any other good yii developer or a development team, say 3-4 developers?

  • http://ehsangazar.ir/ Ehsan Gazar

    Thank you for your good article. that was very interesting, I have been using Yii2 for about 1 month and I found that very fast for developing.

  • http://www.agriya.com/services/yii-development jennifermorrison

    All the 7 reasons are good for me to use YII2. But i am going slowly to learn about YII framework. Just last week only i know about why use Yii framework for web development that article is written by me.http://yiidevelopmentservices.blogspot.in/2015/06/why-use-yii-framework-for-development.html . is hould be know about some more things about YII framework. After that i will go to learn about YII2.

  • Mārtiņš Briedis
  • http://www.xpertdeveloper.com/ Avinash

    Nice article indeed. I have gone through all the comments over here and seems like people are comparing Yii2 over Laravel. But what I was thinking is both are having a ncie feature list and I am respecting both of them. As those are developed by group of great mind and yes after consuming lots of coffee. :)

    I do work on almost of all major framework available in market except Zend and I really enjoy working with all those. Each framework is having their strong and weak points compared to other frameworks and this is going to be never ending discussion even after 10 years from now. :)

    Anyways I am not pointing to anyone over here but putting in my views.

  • http://www.incomepitbull.com/ Wade Shuler

    Not all frameworks are for the same job. Yii2 is for prototypes and start-ups. If you build a project in Yii2 and it takes off, you “should” convert it to a better system that fits the needs more appropriately (when budget and resources permit). This may mean ditching PHP completely and moving to RoR, Node, C, etc. Yii2 is light weight, highly extendable, has plenty of extensions, and it’s super easy to make your own. After a year or so in Yii2, you should have a handful of your own custom made extensions. In benchmark tests I have seen, though sadly I can’t recall where to cite the sources, It out performs Laravel, Symphony, and Zend. Implement caching, make use of Amazon S3 and other cloud based resources, put it on a scalable cloud host, and Yii2 can take a serious beating and purr like a kitten. If your site becomes the next Pinterest or something, then you would need to schedule and upgrade in the future. You would need to do that with Laravel, Symphony, and Zend was sooner than you would with Yii2.

    The main reason I prefer Yii2, is because I can get in and out quickly. The layout just makes sense. In the case of Composer, you must remember that Yii2 basic and Yii2 advanced ARE NOT THE FRAMEWORK. The framework is sitting inside the vendor bin. What you are actually working in, is a base app itself. If you don’t like it, make your own app to work with the framework.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in PHP, once a week, for free.