我正在使用 Yii2 基本模板构建 REST API。我收到一个错误:
exception 'yii\base\InvalidArgumentException' with message 'Response content must be a string or an object implementing __toString().' in /Users/aurasix/ASX-Startups/ASX-CMS/asx-api-yii/vendor/yiisoft/yii2/web/Response.php:1062
Copy Stacktrace Search Stackoverflow Search Google Exception
Invalid Argument – yii\base\InvalidArgumentException
Response content must be a string or an object implementing __toString().
我正在关注 yii2 网站上的指南:https ://www.yiiframework.com/doc/guide/2.0/en/rest-resources
尝试使用集合,以便将来使用分页和排序,我错过了什么吗?
我知道如果我使用 ActiveController 可能会更容易,但我想了解整个过程,这就是我使用 Controller 的原因。我也想要完全控制,我认为 ActiveController 将通过定义模型来发布所有方法,对吧?
我的控制器我不是从 ActiveController 而是从 Controller 扩展它
namespace app\modules\v1\controllers;
use yii\web\Controller;
use app\modules\v1\models\Blog;
use yii\data\ActiveDataProvider;
class BlogController extends Controller {
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
public function actionIndex() {
return new ActiveDataProvider([
'query' => Blog::find()
]);
}
}
我的模型:
namespace app\modules\v1\models;
use yii\db\ActiveRecord;
use yii\web\Linkable;
class Blog extends ActiveRecord implements Linkable {
public static function tableName() {
return 'blog_post';
}
public function fields() {
return [
'id',
'slug',
'title',
'full_content'
];
}
public function extraFields() {
return [
'publish_date',
'short_content'
];
}
public function getLinks() {
return [
];
}
}
在 config.php
'response' => [
'formatters' => [
\yii\web\Response::FORMAT_JSON => [
'class' => 'yii\web\JsonResponseFormatter',
'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
],
],
],
'urlManager' => [
'enablePrettyUrl' => false,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/blog',
'pluralize'=>false
]
],
]