简体   繁体   English

如何使用 Cakephp 访问 REST controller 4

[英]How to access REST controller with Cakephp 4

I'm trying to set up a simple REST GET API that would provide all the data in my "Hierarchies" table with CakePHP4, following https://book.cakephp.org/4/en/development/rest.html I'm trying to set up a simple REST GET API that would provide all the data in my "Hierarchies" table with CakePHP4, following https://book.cakephp.org/4/en/development/rest.html

Here is my /config/routes.php file这是我的 /config/routes.php 文件

$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
    $builder->connect('/', ['controller' => 'Accueil', 'action' => 'index', 'index']);
    $builder->connect('/pages/*', 'Pages::display');
    $builder->fallbacks();
});
$routes->scope('/api', function (RouteBuilder $routes) {
    $routes->setExtensions(['xml', 'json']);
    $routes->resources('Hierarchies');
});

Here is my Controller/HierarchiesController.php这是我的控制器/HierarchiesController.php

class HierarchiesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function index(){
        $recipes = $this->Hierarchies->find('all');
        $this->set([
            'recipes' => $recipes,
            '_serialize' => ['recipes']
        ]);
    }
}
  1. Does the order on my routes.php make sense?我的 routes.php 上的顺序是否有意义? Is it alright?没事吧?
  2. Is something needed in Template/Hierarchies/index.php? Template/Hierarchies/index.php 中是否需要一些东西?
  3. what would be the url to test the endpoint?什么是 url 来测试端点?

Thanks谢谢

Use in routes /config/routes.php在路由中使用 /config/routes.php

$routes->scope('/api', function (RouteBuilder $routes) {
  $routes->setExtensions(['xml', 'json']);
  $builder->connect('/hierarchies/index', ['controller' => 'Hierarchies','action' => 'index']);
});

In controller Controller/HierarchiesController.php add this code:-在 controller Controller/HierarchiesController.php 添加此代码:-

use Cake\Event\EventInterface;

public function beforeFilter(EventInterface $event)
    {
        parent::beforeFilter($event);
        $this->Security->setConfig('unlockedActions', ['index']);
    }

In src/Application.php replace middleware function.在 src/Application.php 中替换中间件 function。

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    { 
        $csrf = new CsrfProtectionMiddleware([
                'httponly' => true,
            ]);
        $csrf->whitelistCallback(function (ServerRequest $request) { 
            // skip controllers 
            $skipedControllers = ['Hierarchies']; // EDIT THIS
            if(in_array($request->getParam('controller'),$skipedControllers)) {
                return true;
            }
            return $request;
        });

        $middlewareQueue
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(new ErrorHandlerMiddleware(Configure::read('Error')))

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(new AssetMiddleware([
                'cacheTime' => Configure::read('Asset.cacheTime'),
            ]))

            // Add routing middleware.
            // If you have a large number of routes connected, turning on routes
            // caching in production could improve performance. For that when
            // creating the middleware instance specify the cache config name by
            // using it's second constructor argument:
            // `new RoutingMiddleware($this, '_cake_routes_')`
            ->add(new RoutingMiddleware($this))

            // Parse various types of encoded request bodies so that they are
            // available as array through $request->getData()
            // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
            ->add(new BodyParserMiddleware())
            
            // Cross Site Request Forgery (CSRF) Protection Middleware
            // https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware
            /*->add(new CsrfProtectionMiddleware([
                'httponly' => true,
            ]));*/
            ->add($csrf);

        return $middlewareQueue;
    }

You url:- {Server url}/{Project Name}/hierarchies/index.json你 url:- {Server url}/{Project Name}/hierarchies/index.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM