繁体   English   中英

如何在控制器Laravel中调用方法?

[英]How do I call a method in my controller Laravel?

我有一个简单的方法,该方法在控制器中定义。 我需要能够从控制器中调用它

我的控制器代码如下:

public function store(Request $request) {
    $data = $request->except('_token');

$name = "form1_sections/" . $data['nextTab'] . "_form";
parse_str($data['inputs'], $output);
$rules =  $this->call_user_func($data['currentTab']); //need to call section1() 
//here if $data['currentTab'] is section1
$validator = Validator::make($output, $rules);

if ($validator->passes()) {
    return ["view" => view("$name")->render(), "isValid" => true];
} else {
    return ["isValid" => false, "msg" => json_encode([
            'errors' => $validator->errors()->getMessages(),
            'code' => 422
        ])
    ];
}
}

function section1() {
    return [
        'startDate' => 'required| date',
        'endDate' => 'required| date|different:startDate',
        'cv' => 'mimes:pdf,doc,docx'
    ];
}
//alo have section2(), section3() etc.

$ data ['currentTab']返回section1()的字符串。非常感谢您的帮助。

就像您在任何实例化类中一样:

$foo = $this->section1();

现在$foo包含您返回的数组。 您可能还应该将方法表示为protected

由于要动态地基于任意字符串调用方法,因此:

$foo = call_user_func('section1');

还是你的情况

$foo = call_user_func($data['currentTab']');

您不应在请求/响应周期之外调用控制器方法。 并制定了执行命令的时间表,例如inspire命令。

如果您有执行一条逻辑的控制器方法,请将此逻辑放在另一个类中。 然后将此新类注入您需要并使用的控制器操作中。

然后为要执行的任务创建命令。 在命令中注入相同的类,并使用它执行逻辑。

使用PHP artisan your_command_name ,一旦命令your_command_name ,您可以将其添加到计划中: $schedule->command('your_command_name')->hourly();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM