2017-03-07 54 views
-1

我正在用slim 3構建休息API,但我在理解如何執行路由時遇到了一些麻煩。我最初使用get方法在api.com/v1/companies/get和api.com/v1/companies/get/id上正確工作,並在api.com/v1/companies/post中發佈方法,但我重構了所有方法將在api.com/v1/companies/id,並在此重構後,我得到一個405錯誤發佈請求說,只有get方法存在。使用Slim編組路由REST API

所以我做了更多的研究;我在其他slim 3指南中發現的小但突破性不一致的數量有點令人討厭,但它看起來像我的解決方案是map()函數,只是我不知道如何使用它,甚至是官方文檔跳過在我不明白的部分。

這是代碼,打破了它在重構後的樣子:

$app->group('/v1', function() use ($app) { 
    $app->group('/companies', function() use ($app) { 
     $app->get('/{code}', function($request, $response, $args) {...} 
     $app->get('', function($request, $response, $args) {...} 
     $app->post('', function($request, $response, $args) {...} 
    }); 
}); 

而我的第一次嘗試在使用地圖():

$app->group('/v1', function() use ($app) { 
    $app->map(['GET', 'POST', 'PUT', 'DELETE'], '/companies/{code}', function($request, $response, $args) use ($app) { 
     //here's where I don't know what to do 
     if($request->isGet()) { 
      //What goes here? And I seem to be having problems accessing my parameters? 
     } 
    } 
} 

回答

1

此代碼的工作對我來說:

<?php 

use \Psr\Http\Message\ServerRequestInterface as Request; 
use \Psr\Http\Message\ResponseInterface as Response; 

require '../vendor/autoload.php'; 

$app = new \Slim\App; 

$app->group('/v1', function() { 
    $this->map(['GET', 'POST', 'PUT', 'DELETE'], '/companies/{code}', function($request, $response, $args) { 

     if($request->isGet()) { 
      $response->getBody()->write("it's GET"); 
     } 

     if($request->isPost()) { 
      $response->getBody()->write("it's POST"); 
     } 

     if($request->isPut()) { 
      $response->getBody()->write("it's PUT"); 
     } 

     if($request->isDelete()) { 
      $response->getBody()->write("it's DELETE"); 
     } 

     return $response; 
    }); 
}); 

$app->run(); 

請不要在組內使用$ app。在docs中,您可以看到$這個內部組已指向「Slim \ App」的實例。如果按照Slim3文檔中的說明配置,請檢查.htaccess文件。

+0

對於$ this和$ app,我認爲它原本就是$ this,但我在其他地方一直看到$ app。謝謝 – Pacio