在null上调用成员函数getDb()

时间:2018-08-19 08:21:04

标签: php rest yii2 yii2-user

我正在使用Yii2 Framework和dektrium/yii2-user模块来在宁静的环境中处理身份验证。

这是我的API目录结构:

api
├── config
│   ├── api.php
│   ├── bootstrap.php
│   ├── params.php
│   └── routes.php
├── index.php
├── modules
│   └── v1
│       ├── controllers
│       │   └── UserController.php
│       ├── models
│       │   └── User.php
│       └── Module.php
└── runtime

api.php

...
$config = [
    ...
    'components' => [
        'user' => [
            'identityClass'  => 'app\api\modules\v1\models\User',
            'enableAutoLogin'  => false,
        ],
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => require(__DIR__ . '/routes.php'),
        ],
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=DBname',
            'username' => 'DBusername',
            'password' => 'DBpassword',
            'charset' => 'utf8'
        ],
    ],
    'modules' => [
        'v1' => [
            'class' => 'app\api\modules\v1\Module',
            'controllerNamespace' => 'app\api\modules\v1\controllers',
        ],
    ],
    ...
];
...

UserController.php

class UserController extends ActiveController
{
    public $modelClass = 'app\api\modules\v1\models\User';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBearerAuth::className(),
        ];
        return $behaviors;
    }
}

User.php

use dektrium\user\models\User as Base;

class User extends Base
{
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['auth_key' => $token]);
    }
}

虽然我正在尝试通过curl发出HTTP POST请求,

curl -H 'Accept:application/json' -H "Authorization: Bearer <Token>" http://<url>/api/v1/users

我得到的结果是

"name": "Exception",
"message": "Call to a member function getDb() on null",
"code": 0,
"type": "Error",
"file": "<project path>/vendor/dektrium/yii2-user/traits/ModuleTrait.php",
"line": 28,

ModuleTrait.php中的第28行:

public static function getDb()
{
    return \Yii::$app->getModule('user')->getDb();
}

在每个步骤中检查结果时,我发现\Yii::$app->getModule('user')的值为null

您是否知道如何解决此错误?

1 个答案:

答案 0 :(得分:3)

您没有backgroundRect.setSize(100,100); 模块-您可以尝试添加有效的模块:

user