如何为Yii2-basic-template创建REST API

Blo*_*und 6 rest yii2 yii2-basic-app

我想为yii2基本模板创建一个REST API.我按照以下链接.

我创建了一个名为users的控制台,名为UserController

<?php
namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}
?>
Run Code Online (Sandbox Code Playgroud)

并在网络上

   'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    ],
],

        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '4534',
            'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ],
        ],  
Run Code Online (Sandbox Code Playgroud)

我的文件名是restapi所以我尝试了这个url http:// localhost/~user/restapi/web / all我得到的是404页面未找到错误.任何帮助,将不胜感激

ank*_*itr 8

Rest Api在Yii2基本应用程序中实现非常简单.请按照以下步骤操作.这段代码对我有用.

申请结构

yourapp
+ web
+ config
+ controllers
...
+ api
  + config
  + modules
    + v1
      + controllers
  .htaccess
  index.php
Run Code Online (Sandbox Code Playgroud)

API/index.php文件

<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

// Use a distinct configuration for the API
$config = require(__DIR__ . '/config/api.php');

(new yii\web\Application($config))->run();
Run Code Online (Sandbox Code Playgroud)

API /的.htaccess

Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php
Run Code Online (Sandbox Code Playgroud)

API /配置/ api.php

<?php

$db     = require(__DIR__ . '/../../config/db.php');
$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'name' => 'TimeTracker',
    // Need to get one level up:
    'basePath' => dirname(__DIR__).'/..',
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // Enable JSON Input:
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                     // Create API log in the standard log dir
                     // But in file 'api.log':
                    'logFile' => '@app/runtime/logs/api.log',
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/project','v1/time']],
            ],
        ], 
        'db' => $db,
    ],
    'modules' => [
        'v1' => [
            'class' => 'app\api\modules\v1\Module',
        ],
    ],
    'params' => $params,
];

return $config;
Run Code Online (Sandbox Code Playgroud)

API /模块/ V1/Module.php

<?php
// Check this namespace:
namespace app\api\modules\v1;

class Module extends \yii\base\Module
{
    public function init()
    {
        parent::init();

        // ...  other initialization code ...
    }
}
Run Code Online (Sandbox Code Playgroud)

API /模块/ V1 /控制器/ ProjectController.php

<?php
namespace app\api\modules\v1\controllers;

use yii\rest\ActiveController;

class ProjectController extends ActiveController
{
    // We are using the regular web app modules:
    public $modelClass = 'app\models\Project';
}
Run Code Online (Sandbox Code Playgroud)

参考

  • 你将如何访问控制器项目?我的意思是网址是什么? (4认同)

Sal*_*ani 5

使用这些配置:

'rules' => [
    ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
Run Code Online (Sandbox Code Playgroud)

您的资源应在这些url中可用:

http://localhost/~user/restapi/web/users

http://localhost/~user/restapi/web/users/1

  • 注意:除非您配置yii\rest\UrlRule::$pluralize属性,否则Yii会自动将用于端点的控制器名称复数。

另外,如果使用apache服务器,则需要在启用Pretty Urls之前通过将.htaccess具有此内容的文件添加到文件web夹中来配置服务器(请使用以下链接,如果使用nginx,请参见下面的链接):

# Set document root to be "basic/web"
DocumentRoot "path/to/basic/web"

<Directory "path/to/basic/web">
    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # 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

    # ...other settings...
</Directory>
Run Code Online (Sandbox Code Playgroud)

您提供的链接的文档中未描述此部分,因为您希望确实遵循了“ 安装和服务器配置”部分

http://www.yiiframework.com/doc-2.0/guide-start-installation.html#configuring-web-servers