如何在Laravel应用程序中从同一控制器调用其他函数?

我是Laravel的新手,我得到了Laravel项目,我需要在其中添加一些新功能。以前在该项目上工作过的人甚至没有在代码中留下任何评论,现在我必须针对这些功能制定自己的方案。 我有一个控制器,定义了一些功能(仪表板,show_project,save_project等),在我的一个功能中,我需要使用调用其他功能的结果。

在具体示例中,调用是通过“ http://127.0.0.1:8000/username/project_slug”进行的-有一个“保存”和发布功能的按钮,在 onClick 事件上被调用。通常需要在“ http://127.0.0.1:8000/username/project_slug/svg”上调用该函数的输出,该函数返回一个视图。

为了更好地理解,有一个流程示例:
用户想保存他/她的项目(UML图),但是为了拥有缩略图,将调用一个生成视图(SVG格式)的函数,其想法是获取页面的HTML内容,位于“ http://127.0.0.1:8000/username/project_slug/svg”上,并将其传递给另一个API,以便生成图像。

到目前为止,我尝试使用 cURL file_get_contents file_get_html 渲染方法,但是当我返回输出,服务器仅保持等待状态,不显示任何错误消息。

//The both functions are in ProjectController.php

/**
 * A function,for saving the json file,where the whole of the diagram 
 * components are described. From the frontend we receive the project_id and  
 * the project_data(the json content).
 */
public function save_project(Request $request) {
        $input = $request->only(['project_id','project_data']);

        /*
          Here we need to call the other function,to render the HTML content
          and to pass it to the other API. Then we save the result with the
          other information.
        */

        /*
          What I've tried?
          $new_link = 'http://' . $_SERVER['HTTP_HOST'] . "/$username" 
                                              ."/$project_slug" . "/svg";
          $contents = file_get_contents($new_link);
          return $contents;
        */

        //In the same way with cURL.

        $project = Project::where('user_id',session('userid'))
                          ->where('id',$input['project_id'])->first();
        $project->project_data = json_encode($input['project_data']);
        if($project->save()) {
            return ["status"=>"saved"];
        }
        else {
            return ["status"=>"error"];
        }
    }

/**
 * A function,which takes the the Json content (project_data) from the 
 * database and passes it to the view,where the Json is transformed in HTML 
 * tags. 
 */
public function generate_svg(Request $request,$username,$project_slug) {
        if(session('username')!=$username) {
            return redirect("/");
        }

        $userid = session('userid');

        $project = Project::where([
            'user_id' => $userid,'slug' => $project_slug,])->first();

        if(!is_null($project)) {
            return view('svg',compact('project'));        
        }
    }

我已经阅读了一些可能的方法,包括“进食”请求,但也许我没有正确理解这个主意:

如果我需要从控制器向控制器内的其他功能发出 Guzzle 请求,我是否需要API配置?

我的意思是?例: 在保存项目之前,用户位于此URL地址“ http://127.0.0.1:8000/hristo/16test”上。在控制器内部,我在会话变量中具有令牌,用户名(hristo),并且我可以从URL获取project_name(16test),但在将该URL传递给 generate_svg 函数之后,没有任何指示错误或成功。

所以我缺少某种令牌信息?

oxforever 回答:如何在Laravel应用程序中从同一控制器调用其他函数?

如果您只需要其他功能的响应,则可以使用

$response = $this->generate_svg($request,$username,$project_slug);

如果您需要从其他控制器使用此功能,则可以使用

app('App\Http\Controllers\UsernameController')->generate_svg($request,$project_slug);
本文链接:https://www.f2er.com/3137487.html

大家都在问