为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
冉冉说 2021-05-06 18:23:45
有人请帮助我启发拉拉夫!在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); }有什么办法可以做到这一点?
查看完整描述

2 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

用 {};


请在循环中尝试以下操作:


$fn = strtolower($functionName)

$ctrl::{$fn}($request);

您也可以调用属性。


$ instance-> {'attribute_name'};


查看完整回答
反对 回复 2021-05-21
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

路线

正确的方法是为您的对象定义一个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。


查看完整回答
反对 回复 2021-05-21
  • 2 回答
  • 0 关注
  • 155 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信