Creating reusable controllers
In Yii you can create reusable controllers. If you are creating a lot of applications or controllers that are of the same type, moving all common code into a reusable controller will save you a lot of time.
In this recipe we will create a simple reusable api controller that will implement a simple JSON CRUD API for a model. It will take input data from POST and GET and will respond with JSON data and a corresponding HTTP response code.
Getting ready
Create a fresh Yii application using
yiic webapp.Create a database and execute the following SQL:
CREATE TABLE `post` ( `id` int(11) NOT NULL auto_increment, `text` text, `title` varchar(255) default NULL, PRIMARY KEY (`id`) );
Configure the application to use the database created and generate a model using Gii. In our example we'll use the
Postmodel, but you can use any model you want.
How to do it...
Create
protected/extensions/json_api/JsonApiController.php:<?php class JsonApiController extends CController...