简体   繁体   English

另一个控制器中的呼叫控制器功能

[英]Call controller function in another controller

I've a PermissionController with a permission() function like below, and i want to call the permission() function in another controller. 我有一个带有permission()函数的PermissionController ,如下所示,我想在另一个控制器中调用permission()函数。 How can i call my permission() function to another controller ? 如何将我的permission()函数调用到另一个控制器?

here my PermissionController 这是我的PermissionController

class PermissionController extends Controller
{
    public function permission(){
    $checkPermission = User::leftJoin('employees', 'employees.user_id', '=', 'users.id')
    ->leftJoin('positions', 'employees.position_id', '=', 'positions.id')
    ->leftJoin('divisions', 'employees.division_id', '=', 'divisions.id')
    ->where(function($query){
        $query->where('division_name', 'Sales')
                ->orWhere('division_name', '=', 'Project Management')
                ->orWhere('position_name', '=', 'Dept Head');
    })
    ->get();

    }   
}

Create new Helper (eg PermissionHelper.php ) then move the funtion to it and call it where you want using : 创建一个新的Helper(例如PermissionHelper.php ),然后将功能移到其中,并使用以下命令将其调用:

PermissionHelper::permission();

Hope this helps. 希望这可以帮助。

I think your function should be in one of your model since you're only getting value. 我认为您的功能应该属于您的模型之一,因为您只会获得价值。

This will me more relevant according to MVC. 根据MVC,这与我更相关。

Having it in your User model will let you use it on every instance of your application with a single call. User模型中拥有它可以让您通过一个调用在应用程序的每个实例上使用它。

You can call another controller's method, but this is terrible practice. 您可以调用另一个控制器的方法,但这是很糟糕的做法。 Move you code to a model and call it with: 将您的代码移至模型并使用以下命令进行调用:

class PermissionController extends Controller
{
    public function permission()
    {
        $checkPermission = User::getEmployeePermissions();
    }
}

Do the same in other controllers' methods. 在其他控制器的方法中执行相同的操作。

You can call your PermissionController's "permission" method this way : 您可以通过以下方式调用PermissionController的“ permission”方法:

app(PermissionController::class)->permission();

However, be aware that this method isn't a good idea at all . 但是,请注意,这种方法是不是一个好主意。

You have multiple refactoring options available ranging from the use of a helper class, a method on the concerned model or using a laravel job. 您可以使用多种重构选项,包括使用帮助程序类,有关模型上的方法或使用laravel作业。

Try to do like this 尝试这样做

public function __construct(PermissionController $permission_controller)
{
  parent::__construct();
  $this->permission_controller = $permission_controller;
}

Call any method like this 调用任何这样的方法

$this->permission_controller->permission();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM