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

时间:2019-02-13 05:20:18

标签: php laravel controller

我有一个控制器文件,该文件具有一个函数login()可以登录(验证并返回令牌)到某个第三方门户。现在,我想在自定义命令中重用该控制器功能。请提出建议。我的控制器文件看起来像这样-

<?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
}

位于app / Console / Commands中的我的自定义命令文件看起来像这样-

<?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.
}
?>

我在线搜索了类似的解决方案,但无法解决任何问题

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式执行此操作:

方法1
Use Trait

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

然后,您可以在类中使用函数,如下所示:

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
}

在您的命令中将如下所示:

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
   }
}

方法2

如果控制器类没有任何特殊的constructor,则可以在command内部的控制器中创建实例,然后按如下所示调用方法:

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();
   }
}