Yii2 + AngularJS in a single application - how?

Neel Shah picture Neel Shah · Aug 13, 2015 · Viewed 16.3k times · Source

I have experience with both Yii 2 and AngularJS, but separately. I have two questions:

Is it possible to use AngularJS in Yii 2's view? I am asking possible instead of feasible, because I think the problem may have arrived at routing.

Also, is it fair enough (for performance) to use Yii 2 and AngularJS together? (Both are MVC so for modular, manageable code.)

I searched for a long time, but I was unable to find any proper resource. What is the explanation!

Answer

Salem Ouerdani picture Salem Ouerdani · Aug 13, 2015

YES, you can use AngularJS in Yii 2 views after implementing a different rooting approach. Here is a tutorial to start with.

But NO, I don't recommend doing so (while both Yii 2 and AngularJS are great frameworks with native support of REST). So the proper way is to use AngularJS to build your frontend and use Yii 2 just to provide a server API. Here is a good structure to do so:

Structure by @AlekseiAkireikin from this Stack Overflow post

   project/
     backend/        // Yii 2 application
       web/          // Public visible backend folder
         index.php   // Entry point
       config/
       controllers/
       models/
       ...
     frontend/
       app/          // Your AngularJS application here
         css/        // Styles (.less or .css)
         img/        // Images
         lib/        // Third-party libraries such as jQuery or AngularJS
         js/         // .js files (controllers, services, etc.)
         partials/   // Templates (.html)
         index.html
       tests/        // AngularJS tests
       node_modules/
       ...

The Yii RESTful API framework will provide a clean API which can communicate with your built-in AngularJS application or maybe a future mobile app or even providing resources and/or services to other websites or software. If you care about performance then go with both and use REST. A well-structured RESTful application is great to easily build a good caching system with a flexible strategy behind. You can even host your backend and database on a server (like Amazon EC2) providing only JSON (and/or XML) data for minimum bandwidth use, and having your frontend stored on an optimized CDN (like Amazon S3 or other CDN provider) with lower cost and faster answers.

Here are two examples implementing AngularJS and Yii 2 within REST: this and this.