I have developed an app in Yii2 that is as a backoffice for a Travel Agency.
I have used the basic start template, and used gii (code generator) to create the CRUDS for the models (Hotels, HotelRooms, HotelImages, etc)
I also want to create two different front-end applications (one for retail, and the other for other agencies), and I thought to separate it from the backend (maybe an angular.js app) and get the info through REST could be a good approach.
So I want to use the API Rest based on the models made with gii.
How can I achieve this?
I have read this:
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
and It says that I have to switch the controllers.
Currently I have (generated with gii)
class HotelController extends Controller
and reading the guide it says that I have to use
class HotelController extends ActiveController
but if I make this change, the backoffice does not work anymore.
What would be the best approach?
Make another APIHotelController that extends ActiveController?
Can I merge (in some sort of way) with the gii generated controller?
Any other way to achieve this separation of layers (back-front) ?
Thanks!
The most elegant solution I know so far to build a REST API Yii2 web app without messing up with the existent code or the routes configurations is by building a REST API as a separate sub-application containing MVC elements by itself, which means in Yii's world : as a module.
You already have a working code, accessible within the web
folder, it has it's own Entry Scripts within the index.php
file, its own server configurations (.htaccess
file if using apache) and its own app configurations within the config
folder to which your app will depend before parsing your URL's and rendering your view files within their related controllers
and models
.
So the idea is to create a new web
folder, lets call it api
for example, with its own Entry Scripts file, own server configurations, own config
folder and own controllers
extending the ActiveController class.
Then both, your web
app and api
service will share the same models
files to validate, store or retrieve data.
Your app will move from this basic template based structure :
+ assets
+ config
+ controllers
+ models
+ views
+ web
...
To this new structure (from the tutorial linked below) :
+ web
+ config
+ controllers
...
+ api
+ config
+ modules
+ v1
+ controllers
.htaccess
index.php
You will need then to register your api
service as separate module in order to work and being initialized by Yii.
Then you will use different URLs to get to your web
app and related views
or Rest api
and related json/xml outputs respectively within http://[your_path]/web/controller/action
or http://[your_path]/api/v1/controller/action
(url structure depends on your web and api configs).
In order to implement the necessary code, here is a great step by step tutorial. It uses the basic template structure and follows yii's api versionning approach (the v1
folder).