doufei3152 2019-02-12 21:20
浏览 48
已采纳

如何在自定义命令中重用laravel控制器代码

I have controller file that has a function login() that logs in(authenticates and returns a token) to some third party portal. Now i want to reuse that controller function in a custom command. Please suggest how to do so. My controller file looks like this-

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class mmt extends Controller {
public function login() {
 //code to login to third party portal
 // returns a token after successful login
}

my custom command file located in app/Console/Commands looks like this-

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RcvSurveyEmails extends Command {
   protected $signature = 'RcvSurveyEmails:name';
   protected $description = 'command description here';
   public function handle(){
  //I need to use the login() function here and get the token.
}
?>

I search online for similar solution but could not fine any

  • 写回答

1条回答 默认 最新

  • duanqiu3800 2019-02-12 22:23
    关注

    You can do this In two Ways:

    Method 1
    Use Trait

    trait LoginTrait{
       public function Login(){
       //put your code here
       }
    }
    

    And After that you can use your function inside your class like below:

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    class mmt extends Controller {
      use LoginTrait;//login is now available inside your class
    
      //rest of your codes
    }
    

    And In Your Command It's Going to be like below:

    namespace App\Console\Commands;
    use Illuminate\Console\Command;
    class RcvSurveyEmails extends Command {
       use LoginTrait;//login Function is now avaiable inside your Command and you can call it
       protected $signature = 'RcvSurveyEmails:name';
       protected $description = 'command description here';
    
       public function handle(){
       login();//login function
       }
    }
    

    Method 2

    In case that your controller class doesn't have any special constructor you can create an instance from your controller inside your command and then call your method like below:

    namespace App\Console\Commands;
    use Illuminate\Console\Command;
    use App\Http\Controllers\mmt;
    class RcvSurveyEmails extends Command {
       protected $signature = 'RcvSurveyEmails:name';
       protected $description = 'command description here';
    
       public function handle(){
       $controller = new mmt();//your controller name
       $controller->login();
       }
    }
    
    
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部