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

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害