 |
[PHP]
callback ซ้อน callback ทำอย่างไรครับ? |
|
 |
|
|
 |
 |
|
โค้ดที่จะต้องเขียนปกติมันเป็นอย่างนี้ครับ
Code (PHP)
01. $app = new \Slim\App();
02. $app ->group( '/users/{id:[0-9]+}' , function () {
03. $this ->map([ 'GET' , 'DELETE' , 'PATCH' , 'PUT' ], '' , function ( $request , $response , $args ) {
04.
05. })->setName( 'user' );
06. $this ->get( '/reset-password' , function ( $request , $response , $args ) {
07.
08.
09. })->setName( 'user-password-reset' );
10. });
ทีนี้ผมจะให้ทำเป็นแบบไดนามิค คือกำหนดผ่าน array แล้ว loop callback เอา
ตัวอย่าง array
Code (PHP)
1. $routes = [
2. '/' , [
3. [
4. '' => [ 'get' , '\Modules\Home\Controllers\IndexController:indexAction' ],
5. '/somewhere' => [ 'get' , 'Not:exists' ],
6. ]
7. ]
8. ]
ตัวอย่างโค้ดที่จะแปลง array เป็น callback class
Code (PHP)
01. foreach ( $routes as $path => $routeArgs ) {
02. if (isset( $routeArgs [0]) && is_array ( $routeArgs [0])) {
03.
04. global $aaa ;
05. $aaa = $routeArgs [0];
06. call_user_func([ $App , 'group' ], $path , function () {
07. global $aaa ;
08. foreach ( $aaa as $each_group_path => $each_group_args ) {
09. call_user_func([ $this , $each_group_args [0]], $each_group_path , $each_group_args [1]);
10. }
11. });
12. } else {
13.
14.
15. }
16. }
17. unset( $path , $routeArgs );
ทีนี้คือมันไม่สำเร็จ มันกลายเป็น not found เนื่องจากเหมือนกำหนดไม่ถูก แต่ถ้าเขียนตรงๆลงไป เช่นตย.นี้ดันเรียกเจอ
Code (PHP)
1. $App ->group( '/' , function () {
2. $this ->any( '' , '\Modules\Home\Controllers\IndexController:indexAction' );
3. $this ->get( '/somewhere' , 'Not:exists' );
4. });
อย่างข้างบนนี่มันเจอ คือที่กำหนดไปมันถูกแล้ว Controller:method มีอยู่ถูกต้อง แต่ทำยังไงให้มัน callback ได้ครับผม?
Tag : PHP
|
ประวัติการแก้ไข 2017-04-18 20:02:35
|
 |
 |
 |
 |
Date :
2017-04-18 20:01:46 |
By :
mr.v |
View :
960 |
Reply :
2 |
|
 |
 |
 |
 |
|
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|

|
 |
 |
 |
 |
Date :
2017-04-19 11:39:05 |
By :
mr.win |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|