gpt4 book ai didi

laravel-4 - 在 laravel 中编写需要在任何 Controller 之前执行的函数

转载 作者:行者123 更新时间:2023-12-04 01:55:54 41 4
gpt4 key购买 nike

你好,我正在用 laravel 做一个网站。我正在尝试做一个需要在任何 Controller 之前执行的函数。

例子:我有像

这样的功能
function xyz(){
//do code here
}

此功能需要在用户通过刷新页面或执行一些 ajax 请求时在站点上执行。

我知道 codeigniter 有一种方法可以使用 hook 来做到这一点

$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => array('beer', 'wine', 'snacks')
);

laravel 中有什么方法可以做到这一点?

最佳答案

您可以使用 Laravel 中间件来实现这一点。中间件可以为所有 Controller /路由注册为全局,并允许您执行该功能(或者您可以通过使用路由器组为路由子集注册它)。

例子:

<?php

namespace App\Http\Middleware;

use Closure;

class MyMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// call your function
$this->xyz();

return $next($request);
}

public function xyz()
{
// do something
}
}

参见 Laravel documentation on Middleware .

关于laravel-4 - 在 laravel 中编写需要在任何 Controller 之前执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36354689/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com