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