Yii 2.0 Restful Web Service Api

2020-03-07 07:27发布

问题:

Anyone using the integrated RESTful Web Service in Yii 2.0(beta)?

The instructions in the official documentation looks simple but it didn't work for me: I'm using the basic template, have used the gii module to create a simple 'category' model extending ActiveRecord, then i created the CategoriesController extending the 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';
}

Now the model Category is assigned to the $modelClass property which will be needed by the ActiveController Class to relate it with the already defined CRUD actions like index or view:( see ActiveController::actions() )

My UrlManager configs looks like:

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

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

        ],

Because my webserver's documentRoot and my webapp are in separate folders, my htaccess file under the WEB folder looks like:

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 to false are just working fine, but when trying to access to localhost/~salem/alpha2/web/categories i'm having the following error:

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

Any one have any idea about what i'm doing wrong??

Thanks

回答1:

The answer was in the same docs linked above: "...When creating a new controller class, a convention in naming the controller class is to use the type name of the resource and use singular form. For example, to serve user information, the controller may be named as UserController..." i desabled the enableStrictParsing, removed Rules, then renamed my controller to CategoryController now! it works!



标签: php rest yii2