PHP Slim Framework 3 中的范围

PHP scope in Slim Framework 3

我认为这可能是一个简单的问题。有人可以帮助我确定如何最好地访问每个路由器函数中的 $route 变量吗?我正在尝试从数组中添加很多 Slim 3 路由器功能。以下代码来自/src/routes.php:

<?php
// Standard CRUD Routes (based on templates)

$app->group('/api/v1', function () use ($app) {

  $routes = [
    'calendar' => [
      'table' => 'calendar',
      'prefix' => 'cal',
      'sort' => 'cal_name_orig',
      'fields' => ['cal_name_orig','cal_name_tran','cal_public','cal_color'],
      'permRead' => 1,
      'permWrite' => 1
    ],
    'classroom' => [
      'table' => 'classroom',
      'prefix' => 'room',
      'sort' => 'room_name',
      'fields' => ['room_owner_p_id','room_name','room_common','room_capacity_normal','room_capacity_max','room_current_desks'],
      'permRead' => 1,
      'permWrite' => 1
    ]
  ];

  // register all standard routes using above data
  foreach ($routes as $key => $route) {
    echo "<br><br>ROUTE: $key<br>";
    print_r($route);

    // Add Route: retrieve all records
    $app->get('/' . $key . 's', function ($request, $response, $args) {
      return $this->common->getAll($route['table'], $route['prefix'], $route['sort'], $route['permRead']);
    });

    // Add Route: retrieve specific record
    $app->get('/' . $key . '/[{id}]', function ($request, $response, $args) {
      return $this->common->getById($route['table'], $route['prefix'], $args['id'], $route['permRead']);
    });

    // Add Route: create new record
    $app->put('/' . $key . '/new', function ($request, $response, $args) {
      return $this->common->putNew($route['table'], $route['prefix'], $route['fields'], $route['permWrite']);
    });

    // Add Route: update specific record
    $app->post('/' . $key . '/[{id}]', function ($request, $response, $args) {
      return $this->common->postById($route['table'], $route['prefix'], $args['id'], $route['fields'], $route['permWrite']);
    });

    // Add Route: delete specific record
    $app->delete('/' . $key . '/[{id}]', function ($request, $response, $args) {
      return $this->common->deleteById($route['table'], $route['prefix'], $args['id'], $route['permWrite']);
    });
  }

});

如您所料,我得到的错误是 Notice: Undefined variable: route in C:\Wamp\www\ravine\server\src\routes.php on line 46

foreach 循环正在运行并将每个路由显示到屏幕(用于调试目的)。请注意,所有 $this->common-> 函数都是我编写的自定义函数,我相信它们工作正常(只要我可以向它们传递正确的参数)。

我如何 can/should 从 foreach 循环访问 $route

尝试

 $app->put('/' . $key . '/new', function ($request, $response, $args) use ($route) {