简体   繁体   English

调用控制器的 Laravel 索引函数时的自动调用函数

[英]Autocall function when laravel index function of a controller is called

I have a controller class as follows:我有一个控制器类,如下所示:

class Controller extends BaseController{

protected function function1()
{
    //code
}

protected function function2()
{
     //code
}
}

and every controller in the project extends this class such that i can write functions used in multiple controllers in this Controller class.并且项目中的每个控制器都扩展了这个类,这样我就可以在这个 Controller 类中编写在多个控制器中使用的函数。

class RandomController extends Controller{

    public function aCertainFunction()
    {
        $this->function1();
        //code 
    {
}

I now have a function that should be called every time the index function of any controller is called.我现在有一个函数,每次调用任何控制器的索引函数时都应该调用该函数。 One option is that i manually add this function at the start of every index function in the controllers i have and that i keep doing this for every new controller i create in the future but this doesn't seem efficient to me.一种选择是我在我拥有的控制器中的每个索引函数的开头手动添加此函数,并且我会继续为我将来创建的每个新控制器执行此操作,但这对我来说似乎效率不高。

Is there a way to define this function in my Controller class such that every index function in all classes that inherit from this class will automatically call this function?有没有办法在我的 Controller 类中定义这个函数,这样从这个类继承的所有类中的每个索引函数都会自动调用这个函数?

You should definitely take a look at the Events Listening system embedded in the Laravel framework.你绝对应该看看嵌入在 Laravel 框架中的事件监听系统 Let's admit that you want to trigger aCertainFunction() every time function1 or function2 is executed.让我们承认您想在每次执行function1function2时触发aCertainFunction()

You'll have to declare an Event class which will be stored into the namespace App\\Events;您必须声明一个 Event 类,该类将存储到namespace App\\Events; (you don't need to extends Controller at all as it is dedicated to another purpose). (您根本不需要扩展 Controller,因为它专用于另一个目的)。

The public handle function of your Event class will be called to be executed when you trigger the event with the event() function.当您使用event()函数触发事件时,将调用 Event 类的公共handle函数以执行。 Therefore you will declare your aCertainFunction function directly inside your event class (and call it from the handle function).因此,您将直接在事件类中声明aCertainFunction函数(并从handle函数调用它)。 Please take a deep look at How Laravel is handling Events as it is really dedicated to delegate and call them on specific purposes (and that's why we call them "listeners").请深入了解 Laravel 如何处理事件,因为它真正致力于为特定目的委托和调用它们(这就是我们称它们为“侦听器”的原因)。

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

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