Reputation: 539
In docs guides there is example:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
But i dont get it, how to work with actions.
For example:
DataBase has tables with many-to-many relationship (via Junction table).
Сomponent to work with the models and the formation of a common response from multiple tables according to the transmitted data. Can return an array, or an array of objects.
When use it in commands controller, it was like:
class LastTweetsController extends Controller
{
/**
* @param int $count
*
* @throws yii\base\InvalidConfigException
*/
public function actionIndex($count = 10)
{
/** @var TweetLastfinder $tweetLastFinder */
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
/**
* @var TweetShow $tweetShow
*/
$tweetShow = Yii::$app->get('tweetshow');
// For show tweets into terminal:
$tweetShow->showLastTweetsJSON($tweetLastFinder->findLastTweets($count));
}
}
But how i can make same operation in ActiveController (Transmit parameter $count and return result in JSON)?
Upvotes: 4
Views: 10075
Reputation: 1968
To change API's default actions like - create,update,view,index,delete write below code in controller
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
/* Declare actions supported by APIs (Added in api/modules/v1/components/controller.php too) */
public function actions(){
$actions = parent::actions();
unset($actions['create']);
unset($actions['update']);
unset($actions['delete']);
unset($actions['view']);
unset($actions['index']);
return $actions;
}
/* Declare methods supported by APIs */
protected function verbs(){
return [
'create' => ['POST'],
'update' => ['PUT', 'PATCH','POST'],
'delete' => ['DELETE'],
'view' => ['GET'],
'index'=>['GET'],
];
}
public function actionIndex($count = 10){
/** @var TweetLastfinder $tweetLastFinder */
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
/**
* @var TweetShow $tweetShow
*/
$tweetShow = Yii::$app->get('tweetshow');
// This will return in JSON:
return $tweetLastFinder->findLastTweets($count);
}
}
In API main config file -
'components' => [
....
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/user',
'tokens' => [
'{id}' => '<id:\\w+>',
'{count}' => '<count:\\w+>',
],
//'pluralize' => false,
'extraPatterns' => [
'POST' => 'create', // 'xxxxx' refers to 'actionXxxxx'
'PUT {id}' => 'update',
'PATCH {id}' => 'update',
'DELETE {id}' => 'delete',
'GET {id}' => 'view',
'GET {count}' => 'index',
],
],
]
],
....
]
In your case you want $count in index action parameter so in url manager you need to define 'count' token just like 'id'
Upvotes: 15