无法将Yii2对象数据作为Json返回

Kir*_*lee 5 php json mongodb yii2

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

控制器类代码:

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

模型类代码:

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'
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ole*_*hov 10

导入响应类:

use yii\web\Response;
Run Code Online (Sandbox Code Playgroud)

通过Yii::$app->response->format之前的设置告诉Yii您想要的格式是什么return

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

回应结果:

{
    "success": true,
    "message": "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

您可以在yii2-cookbook中阅读有关响应格式的信息