【问题标题】:How to access REST controller with Cakephp 4如何使用 Cakephp 4 访问 REST 控制器
【发布时间】:2021-04-02 20:15:36
【问题描述】:

我正在尝试设置一个简单的 REST GET API,该 API 将使用 CakePHP4 提供我的“层次结构”表中的所有数据,遵循 https://book.cakephp.org/4/en/development/rest.html

这是我的 /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');
});

这是我的 Controller/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. routes.php 上的顺序是否有意义?没事吧?
  2. Template/Hierarchies/index.php 中是否需要某些内容?
  3. 测试端点的 url 是什么?

谢谢

【问题讨论】:

  • 您希望您的 CakePHP 应用程序作为 API 和普通 Web 应用程序工作,还是仅作为 API 工作?仅当您需要两者时,才需要 /api 路由。但是,您所有相关的控制器等都应该在他们尊重的命名空间中。
  • @rrd :我希望 CakePHP 应用程序仅作为“层次结构”表的 API 工作。
  • 所以你必须在 /api/Controller/ 创建它的控制器,请看这里:book.cakephp.org/4/en/development/routing.html#prefix-routing

标签: php cakephp-4.x


【解决方案1】:

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

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

在控制器 Controller/HierarchiesController.php 中添加以下代码:-

use Cake\Event\EventInterface;

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

在 src/Application.php 中替换中间件函数。

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

你的网址:-{Server url}/{Project Name}/hierarchies/index.json

【讨论】:

  • Google 员工请注意:遵循这种方法并在您的 Application.php 中将许多回调列入白名单会很快使其混乱。相反,您可能希望在您的config/routes.php 中添加enable (or not) the CSRF middleware per scope and/or prefix。最后,CakePHP 4.3 将引入在控制器中设置中间件的能力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
相关资源
最近更新 更多