我想在我的控制器中添加登录操作,它给我找不到页面错误。 我知道有很多这样的帖子,但还没有人帮助过我。
我的控制器的代码:
<?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'
],
]
],
],
答案 0 :(得分:1)
让我们从模型开始:
<?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