How to use a method in one controller in laravel to call a method in another controller?
仅有的幸福
仅有的幸福 2017-05-16 16:47:42
0
6
780

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?

仅有的幸福
仅有的幸福

reply all(6)
巴扎黑

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

洪涛

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.

PHPzhong

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

PHPzhong

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

迷茫

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

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template