【问题标题】:Yii 2.0 Restful Web Service ApiYii 2.0 Restful Web 服务 API
【发布时间】:2014-05-04 20:44:57
【问题描述】:

有人在 Yii 2.0(beta) 中使用集成的 RESTful Web 服务吗?

官方documentation 中的说明看起来很简单,但对我不起作用: 我使用的是基本模板,已经使用 gii 模块创建了一个简单的 'category' 模型扩展 ActiveRecord,然后我创建了 CategoriesController 扩展 ActiveController

# Content of the file app\controllers\CategoriesController.php

<?php

namespace app\controllers;

use yii\rest\ActiveController;

class CategoriesController extends ActiveController
{
    public $modelClass = 'app\models\Category';
}

现在模型Category 被分配给ActiveController 类需要的$modelClass 属性,以将其与已定义的CRUD 操作(如indexview)关联起来:( 见ActiveController::actions())

我的UrlManager 配置如下:

'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,

            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'categories'],
            ],

        ],

因为我的 webserver 的 documentRoot 和我的 webapp 在不同的文件夹中,所以我的 WEB 文件夹下的 htaccess 文件看起来像:

RewriteEngine on

RewriteBase /~salem/alpha2/web

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php

PrettyUrls & showScriptName 为 false 工作正常,但尝试访问 localhost/~salem/alpha2/web/categories 时出现以下错误:

Not Found (#404)
Unable to resolve the request "categories/index".

有人知道我做错了什么吗?

谢谢

【问题讨论】:

    标签: php rest yii2


    【解决方案1】:

    答案在上面链接的同一个文档中:“......当创建一个新的控制器类时,命名控制器类的约定是使用资源的类型名称并使用单数形式。例如,服务用户信息,控制器可能被命名为 UserController...” 我禁用了 enableStrictParsing,删除了规则,然后将我的控制器重命名为 CategoryController 现在!它有效!

    【讨论】:

    • 我也有同样的问题。并使用您的解决方案解决它。但是知道如何为常规 Web 请求和 Web 服务混合 URL 路由吗?
    • @Pelang 如果您将 REST API 构建为独立模块,则可以同时保留两者。那么/web 将像往常一样工作,而您可以拥有一个仅用于 xml 和/或 json 输出的/api 端点。 this tutorial By Joachim Werner 展示了如何做到这一点以及如何为 2 个端点中的每一个使用 2 个配置文件。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多