@@ -300,7 +300,6 @@ public function map($methods, $route, $handler, array $opts = [])
300300 }
301301
302302 $ params = $ this ->getAvailableParams (isset ($ opts ['params ' ]) ? $ opts ['params ' ] : []);
303-
304303 list ($ first , $ conf ) = $ this ->parseParamRoute ($ route , $ params , $ conf );
305304
306305 // route string have regular
@@ -316,6 +315,56 @@ public function map($methods, $route, $handler, array $opts = [])
316315 return $ this ;
317316 }
318317
318+ /**
319+ * register a group restful routes for the controller class.
320+ * ```php
321+ * $router->rest('/users', UserController::class);
322+ * ```
323+ * @param string $prefix eg '/users'
324+ * @param string $controllerClass
325+ * @param array $map You can append or change default map list.
326+ * [
327+ * 'index' => null, // set value is empty to delete.
328+ * 'list' => 'get', // add new route
329+ * ]
330+ * @param array $opts Common options
331+ * @return ORouter
332+ */
333+ public function rest ($ prefix , $ controllerClass , array $ map = [], array $ opts = [])
334+ {
335+ $ map = array_merge ([
336+ 'index ' => ['GET ' ],
337+ 'create ' => ['POST ' ],
338+ 'view ' => ['GET ' , '{id} ' , ['id ' => '[1-9]\d* ' ]],
339+ 'update ' => ['PUT ' , '{id} ' , ['id ' => '[1-9]\d* ' ]],
340+ 'patch ' => ['PATCH ' , '{id} ' , ['id ' => '[1-9]\d* ' ]],
341+ 'delete ' => ['DELETE ' , '{id} ' , ['id ' => '[1-9]\d* ' ]],
342+ ], $ map );
343+ //$opts = array_merge([], $opts);
344+
345+ foreach ($ map as $ action => $ conf ) {
346+ if (!$ conf || !$ action ) {
347+ continue ;
348+ }
349+
350+ $ route = $ prefix ;
351+
352+ // '/users/{id}'
353+ if (isset ($ conf [1 ]) && ($ subPath = trim ($ conf [1 ]))) {
354+ // allow define a abs route. '/user-other-info'. it's not prepend prefix.
355+ $ route = $ subPath [0 ] === '/ ' ? $ subPath : $ prefix . '/ ' . $ subPath ;
356+ }
357+
358+ if (isset ($ conf [2 ])) {
359+ $ opts ['params ' ] = $ conf [2 ];
360+ }
361+
362+ $ this ->map ($ conf [0 ], $ route , $ controllerClass . '@ ' . $ action , $ opts );
363+ }
364+
365+ return $ this ;
366+ }
367+
319368 /*******************************************************************************
320369 * route match
321370 ******************************************************************************/
@@ -379,10 +428,7 @@ public function match($path, $method = 'GET')
379428 }
380429
381430 // handle Auto Route
382- if (
383- $ this ->config ['autoRoute ' ] &&
384- ($ handler = $ this ->matchAutoRoute ($ path , $ this ->config ['controllerNamespace ' ], $ this ->config ['controllerSuffix ' ]))
385- ) {
431+ if ($ this ->config ['autoRoute ' ] && ($ handler = $ this ->matchAutoRoute ($ path ))) {
386432 return [self ::FOUND , $ path , [
387433 'handler ' => $ handler ,
388434 'option ' => [],
0 commit comments