doufei3152 2019-02-13 05: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-13 06: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();
       }
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)