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?
巴扎黑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
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.
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
迷茫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
大家讲道理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