call_user_func_array中传回调函数 标准码农 技术分享 239 views 在slim框架中,定义路由,与对应的PHP入口是通过回调函数来实现的 在多个路由使用相同的逻辑,可以将回调函数抽象出来,类似于js ```php $app->get('/packageV1/goods/search', function(Request $request, Response $response,array $args=[]): Response{ $params = $request->getParams(); list($totalCount, $goods) = GoodsV1Service::list($params); return $response->withJson([ 'code' => Valid::CODE_SUCCESS, 'data' => [ 'total_count' => $totalCount, 'goods' => $goods ] ], StatusCode::HTTP_OK); }); $app->get('/packageV1/goods/search/{goods_category_type}', function(Request $request, Response $response,array $args=[]): Response{ $params = $request->getParams(); list($totalCount, $goods) = GoodsV1Service::list($params); return $response->withJson([ 'code' => Valid::CODE_SUCCESS, 'data' => [ 'total_count' => $totalCount, 'goods' => $goods ] ], StatusCode::HTTP_OK); }); ``` 可以简化为以下形式: ```php function callbackSearch(): \Closure { return function(Request $request, Response $response,array $args=[]): Response{ $params = $request->getParams(); list($totalCount, $goods) = GoodsV1Service::list($params); return $response->withJson([ 'code' => Valid::CODE_SUCCESS, 'data' => [ 'total_count' => $totalCount, 'goods' => $goods ] ], StatusCode::HTTP_OK); }; } call_user_func_array([$app, 'get'], ['/packageV1/goods/search', callbackSearch()]); call_user_func_array([$app, 'get'], ['/packageV1/goods/search/{goods_category_type}', callbackSearch()]); ``` 这里一定要用callbackSearch()的返回值的方式把参数传过去,不能直接写方法名 帮助PHPZlc项目! 与任何开源项目一样, 贡献代码 或 文档 是最常见的帮助方式, 但我们也有广泛的 赞助机会。 0 加入技术群 评论 去登录