更改 API 的默认操作,例如 - 创建、更新、查看、索引、删除
在控制器中写入以下代码
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);
}
}
在 API 主配置文件中 -
'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',
],
],
]
],
....
]
在您的情况下,您希望在索引操作参数中包含 $count ,因此在 url 管理器中您需要定义“count”令牌,就像“id”一样