无法获得以Json形式返回的Yii2对象数据


Not able to get Yii2 object data returned as Json

我是Yii2框架和PHP的新手。当我尝试从服务器检索模型数据作为json时,我得到一个空结果。但是,当我使用var_dump时,我得到一个非空的结果。

控制器类代码:

public function actionIndex() {          
    $client = new Client();
    $client->name = "ajith";
    echo json_encode($client);
}

模型类代码:

class Client extends 'yii'mongodb'ActiveRecord {
    public static function collectionName() {
        return ['gym', 'client'];
    }
    public function attributes() {
        return ['_id', 'name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'];
    }
    public function rules() {
        return [
            [['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
        ];
    }
    public function attributeLabels() {
        return [
            '_id'  => 'ID',
            'name' => 'Name',
            'age'  => 'Age',
            'sex'  => 'Sex',
            'phoneno'  => 'Phoneno',
            'email'    => 'Email',
            'address'  => 'Address',
            'location' => 'Location'
        ];
    }
}

当我使用URL路径pathToServer/web/client时,我得到的结果显示为{}。为什么会这样呢?我使用MongoDB作为数据库

导入响应类:

use yii'web'Response;
use Yii;

通过在return之前设置Yii::$app->response->format来告诉Yii您想要的结果格式

public function actionIndex() {    
    Yii::$app->response->format = Response::FORMAT_JSON;        
    $data = ["success" => true, "message" => "Hello World"];
    return $data;
}

响应结果:

{
    "success": true,
    "message": "Hello World"
}

您可以在yii2-cookbook

中阅读有关响应格式的内容。