2015-09-17 23 views
6

Tôi muốn tạo một API REST cho mẫu cơ bản yii2. Tôi đã theo dõi link sau đây.Cách tạo API REST cho mẫu Yii2-basic

Tôi tạo ra một bảng tên users, một bộ điều khiển tên UserController

<?php 
namespace app\controllers; 

use yii\rest\ActiveController; 

class UserController extends ActiveController 
{ 
    public $modelClass = 'app\models\User'; 
} 
?> 

và trong các trang web

'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', 
    ], 
     ], 

tên file của tôi là restapi vì vậy tôi cố gắng url này http://localhost/~user/restapi/web/ tất cả tôi nhận được là một Lỗi 404 không tìm thấy trang. Mọi trợ giúp sẽ được đánh giá cao

Trả lời

4

Với những cấu hình:

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

nguồn lực của bạn nên có sẵn trong những url:

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

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

  • Lưu ý: Yii sẽ tự động pluralize tên điều khiển cho sử dụng ở điểm cuối trừ khi bạn định cấu hình tài sản yii\rest\UrlRule::$pluralize không làm như vậy.

Ngoài ra, bạn cần phải cấu hình máy chủ của bạn trước khi kích hoạt url Khá bằng cách thêm một tập tin .htaccess với nội dung này vào thư mục web của bạn nếu sử dụng apache máy chủ (xin tham khảo liên kết bên dưới nếu sử dụng 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> 

Phần này không được mô tả trong tài liệu liên kết mà bạn cung cấp như nó đã được mong đợi rằng bạn đã làm theo các cài đặt cấu hình phần & máy chủ:

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

6

Api còn lại rất đơn giản để triển khai trong ứng dụng cơ bản Yii2. Chỉ cần làm theo các bước dưới đây. Mã này đang hoạt động cho tôi.

cấu trúc ứng dụng

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'; 
} 

reference

+4

làm thế nào bạn sẽ truy cập vào dự án điều khiển? Ý tôi là url sẽ là gì? – Bloodhound