search

Home  >  Q&A  >  body text

How to use a method in one controller in laravel to call a method in another controller?

What should I do if a method in one controller in laravel calls a method in another controller?

For example:
AaaController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AaaController extends Controller
{
    public function aaa()
    {
        //...
    }
}

BbbController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BbbController extends Controller
{
    public function bbb()
    {
        //这里要调用aaa(),应该怎么做?
    }
}

How should the bbb() method in BbbController call the aaa() method in AaaController?

仅有的幸福仅有的幸福2780 days ago803

reply all(6)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 16:49:42

    This shows that you have not extracted the logic in the aaa method, orm can be placed in Repository, and logical operations can be placed in service

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 16:49:42

    This is usually not recommended.

    $ctrl = \App::make(\App\Http\Controllers\AaaController::class);
    \App::call([$ctrl, "aaa"]);

    Why is it so complicated instead of just creating a new AaaController and calling the method directly? Because we have to deal with dependency injection.

    reply
    0
  • PHPz

    PHPz2017-05-16 16:49:42

    Create an instance of controller A in controller B
    It can be used this way, but I don’t know if it is legal or not

    reply
    0
  • PHPz

    PHPz2017-05-16 16:49:42

    (new AaaController ())->aaa();

    reply
    0
  • 迷茫

    迷茫2017-05-16 16:49:42

    You can build a BaseController, and the other two congtrollers jointly inherit this controller. Some public methods can be placed in the BaseController, or add a helper file

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 16:49:42

    If you must do this, you can define the called method as a static method. Then the class name is called directly. But I don’t recommend doing this

    reply
    0
  • Cancelreply