CakePHP3 CRUD API和API路由

时间:2019-04-29 21:53:12

标签: crud cakephp-3.x

我正在为我的后端API使用Friends of Cake CRUD插件。我还在路由中使用API​​前缀:

Router::prefix('Api', function ($routes) {
    $routes->extensions(['json', 'xml', 'ajax']);
    $routes->resources('Messages');
    $routes->resources('ReportedListings');
    $routes->fallbacks('InflectedRoute');
});

到目前为止,一切都很好。我的控制器如下:

namespace App\Controller\Api;

use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Core\Exception\Exception;

class MessagesController extends AppController {

    use \Crud\Controller\ControllerTrait;

    public function initialize() {  
        parent::initialize();      
        $this->loadComponent(
            'Crud.Crud', [
                'actions' => [
                    'Crud.Add',
                    'update' => ['className' => 'Crud.Edit']
                ],
                'listeners' => ['Crud.Api'],
            ]
            ,'RequestHandler'
        );     
        $this->Crud->config(['listeners.api.exceptionRenderer' => 'App\Error\ExceptionRenderer']);
        $this->Crud->addListener('relatedModels', 'Crud.RelatedModels');
    }

    public function beforeFilter(Event $event){
        parent::beforeFilter($event);      
    }

    public function add() {      
        return $this->Crud->execute();
    }

当我拨打电话时,如下所示:

[POST] /api/messages.json

我得到一个错误:

Action MessagesController::index() could not be found, or is not accessible.

我改用:

[POST] /messages.json

我没有收到错误,我可以添加一条消息。所以问题是为什么CRUD会使用我的api前缀路由查找索引,并且如何避免这种行为?

1 个答案:

答案 0 :(得分:0)

我发现了问题:

{$UNDEF OVFL} 
...
{$IFOPT Q+} {$DEFINE OVFL} {$Q-} {$ENDIF}
Result := YearOf(dtRef)  * Int64(100000000000) + 
          MonthOf(dtRef) * Int64(10000000000) +
          etc...
{$IFDEF OVFL} {$Q+} {$UNDEF OVFL} {$ENDIF}

“ Api”应该是小写!

Router::prefix('Api', function ($routes) {
     ....
}