gpt4 book ai didi

php - 如何在 yii2 中向 yii\rest\activecontroller 扩展 Controller 添加自定义操作?

转载 作者:行者123 更新时间:2023-12-02 03:10:06 25 4
gpt4 key购买 nike

我想在我的 Controller 中添加登录操作,但它给我的页面未找到错误。
我知道有很多这样的帖子,但还没有人帮助过我。

我的 Controller 的代码:

<?php
// controller for rest apis
namespace app\controllers;
use yii\rest\ActiveController;
use yii\rest\Controller;
use yii\web\Response;
//use yii\web\Controller;
use app\models\UserMaster;

//class UserController extends Controller
class UserController extends ActiveController
{
public $modelClass = 'app\models\UserMaster';
public $pluralize = false;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
public function actionLogin(){
return UserMaster::find()->all();
}
public function login(){
return UserMaster::find()->all();
}
}
?>

来自 config/web.php 的代码:
 'urlManager' => [
'enablePrettyUrl' => true,
'class'=>'yii\web\UrlManager',
'showScriptName' => false,

//for specifying rest api model to be used
//and by pluralize=false we can use with singular name rather than plural as default (users)
'enableStrictParsing' => true,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize'=>false,
'extraPatterns' => [
'GET /user/login/' => 'login', // 'xxxxx' refers to 'actionXxxxx'
],
]
],
],

最佳答案

让我们从模型开始:

<?php
namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
* My UserMaster model
*/
class UserMaster extends ActiveRecord
{

public static function tableName()
{
return 'user_master'; // the name of the table
}

// other code ...
}

然后 UserController.php 将如下所示:
<?php
namespace app\controllers;

use Yii;
use yii\rest\ActiveController;
use app\models\userMaster;

/**
* My User controller
*/
class UserController extends ActiveController
{
// define the model class
public $modelClass = 'app\models\UserMaster';

// add a serializer to make front-end development easier
// public $serializer = [
// 'class' => 'yii\rest\Serializer',
// 'collectionEnvelope' => 'items',
// ];

// the login action
public function actionLogin()
{
return UserMaster::find()->all();
}
}

然后我们这样配置我们的 urlManager:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [

[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
// 'pluralize' => false
'extraPatterns' => [
'GET login' => 'login',
// other patterns
]
],

],
],

现在我们可以通过访问 URI GET /users/login 来使用我们的登录信息。 .更多详情请见 Yii2 REST Quick Start

关于php - 如何在 yii2 中向 yii\rest\activecontroller 扩展 Controller 添加自定义操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com