use*_*588 2 php rest json yii2
在文档指南中有例子:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
Run Code Online (Sandbox Code Playgroud)
但我不明白,如何处理行动.
例如:
DataBase具有多对多关系的表(通过Junction表).
Сomponent根据传输的数据处理模型并从多个表中形成共同响应.可以返回数组或对象数组.
在命令控制器中使用它时,它就像:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
但是我如何在ActiveController中进行相同的操作(传递参数$ count并返回JSON中的结果)?
moh*_*hit 13
要更改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);
}
}
Run Code Online (Sandbox Code Playgroud)
在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',
],
],
]
],
....
]
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你需要$ count in index action参数,所以在url manager你需要定义'count'标记就像'id'
归档时间: |
|
查看次数: |
6997 次 |
最近记录: |