Foreach通过laravel:x中的“ name”执行动作静态功能

有人请帮助我启发拉拉夫!


在LARAVEL控制器中,我定义了静态函数,如下所示:


namespace App\Http\Controllers\MyAPI;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

class MyAPIController extends Controller {


    const acceptMethod = ['GET','POST','PUT','DELETE']


    public function handler(Request $request) {

           $acceptMethod = self::acceptMethod;

           $ctrl = new PromotionController;

           $method = $request->method()


         // This is my question :((

          if ($method == 'GET')

              $ctrl::read($request);

          if ($method == 'GET')

              $ctrl::post($request);

          $ctrl::put($request);

          ... 


          //I want to be like this : 

           foreach($acceptMethod as $method) {

              // Not work 

               $ctrl::($method)($request);

           }



    }


    public static function read(Request $request) {

        return something;

    }


    public static function post(Request $request) {

        return ...;

    }


    public static function put(Request $request) {

        return ...;

    }


    public static function delete(Request $request) {

        return ...;

    }


}

然后我必须使用controll像:


  if ($method == 'get')

      $ctrl::read($request);

  if ($method == 'post')

      $ctrl::post($request);

  $ctrl::put($request);

但是我有一个数组:


我想成为这样:


 $acceptMethod = ['GET','POST','PUT','DELETE'];   

 foreach($acceptMethod as $functionName) {

    // Not work 

    $ctrl::$functionName($request);

 }

有什么办法可以做到这一点?


冉冉说
浏览 157回答 2
2回答

德玛西亚99

用 {};请在循环中尝试以下操作:$fn = strtolower($functionName)$ctrl::{$fn}($request);您也可以调用属性。$ instance-> {'attribute_name'};

潇潇雨雨

路线正确的方法是为您的对象定义一个RESTful资源,以便您获得所有RESTful路由。在你的路线/ api.php中Route::resource('thing','MyAPIController');这将神奇地路由:获取api / thing到index()GET api / thing / create到create()POST api /要存储的东西获取要显示的api / thing / {id}($ id)GET api / thing / {id} / edit to edit()修补程序api / thing / {id}以进行update()删除api / thing / {id} to destroy()如果您有多个要使用REST的对象,则只需为每个对象添加一个控制器。怎么了$ ctrl :: {$ fn}($ request)每年OWASP的注入量始终排在前十位,这开启了潜在的功能注入。您可以通过确保将方法列入白名单来减轻这种风险。但是,我宁愿按照预期的方式使用Laravel。
打开App,查看更多内容
随时随地看视频慕课网APP