如何为 Yii2-basic-template 创建 REST API
How to Create a REST API for Yii2-basic-template
我想为 yii2 基本模板创建一个 REST API。我关注了以下link。
我创建了一个名为 users
的 table,一个名为 UserController
的控制器
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
?>
在网络上
'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',
],
],
我的文件名是 restapi 所以我尝试了这个 url http://localhost/~user/restapi/web/
我得到的只是一个 404 页面未找到错误。任何帮助将不胜感激
Rest Api 在 Yii2 基本应用程序中实现起来非常简单。只需按照以下步骤操作。此代码对我有用。
应用结构
yourapp
+ web
+ config
+ controllers
...
+ api
+ config
+ modules
+ v1
+ controllers
.htaccess
index.php
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();
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
api/config/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;
api/modules/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 ...
}
}
api/modules/v1/controllers/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';
}
使用这些配置:
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
您的资源应该在这些网址中可用:
http://localhost/~user/restapi/web/users
http://localhost/~user/restapi/web/users/1
- 注意:Yii 会自动将控制器名称复数化以用于端点,除非您将
yii\rest\UrlRule::$pluralize
属性 配置为不这样做。
您还需要在启用 Pretty Urls 之前配置您的服务器,如果使用 apache服务器(如果使用nginx请参考下面的link):
# 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>
这部分没有在您提供的 link 文档中描述,因为它期望您确实遵循了 安装和服务器配置部分 :
http://www.yiiframework.com/doc-2.0/guide-start-installation.html#configuring-web-servers
我想为 yii2 基本模板创建一个 REST API。我关注了以下link。
我创建了一个名为 users
的 table,一个名为 UserController
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
?>
在网络上
'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',
],
],
我的文件名是 restapi 所以我尝试了这个 url http://localhost/~user/restapi/web/ 我得到的只是一个 404 页面未找到错误。任何帮助将不胜感激
Rest Api 在 Yii2 基本应用程序中实现起来非常简单。只需按照以下步骤操作。此代码对我有用。
应用结构
yourapp
+ web
+ config
+ controllers
...
+ api
+ config
+ modules
+ v1
+ controllers
.htaccess
index.php
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();
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
api/config/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;
api/modules/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 ...
}
}
api/modules/v1/controllers/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';
}
使用这些配置:
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
您的资源应该在这些网址中可用:
http://localhost/~user/restapi/web/users
http://localhost/~user/restapi/web/users/1
- 注意:Yii 会自动将控制器名称复数化以用于端点,除非您将
yii\rest\UrlRule::$pluralize
属性 配置为不这样做。
您还需要在启用 Pretty Urls 之前配置您的服务器,如果使用 apache服务器(如果使用nginx请参考下面的link):
# 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>
这部分没有在您提供的 link 文档中描述,因为它期望您确实遵循了 安装和服务器配置部分 :
http://www.yiiframework.com/doc-2.0/guide-start-installation.html#configuring-web-servers