A
A
Alexey Bolgov2020-08-09 23:02:20
PHP
Alexey Bolgov, 2020-08-09 23:02:20

Restricting the execution of a function, how to do?

Hello, there is an application that needs to be made so that each function can be executed 3 seconds after the last execution. Breaking my head Carbon can not understand and throttle only in minutes. How to implement something like this?
Here is an example function

public function readNotifications() {
        if(Auth::guest()) return '-1';
        foreach(Notification::where('user_id', Auth::user()->id)->where('read_status', 0)->get() as $notification) {
            $notification->read_status = 1;
            $notification->save();
        }
        return '1';
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zlatoslav Desyatnikov, 2020-08-10
@Alex2412729

Use the `Illuminate\Cache\RateLimiter` class.

$limiter = app()->make(Illuminate\Cache\RateLimiter::class); // Или завозите через DI

$limiterKey = request()->ip() . '_readNotifications';  // Какой-то ключ, по которому будет вестись счётчик

$decayIntervalInSeconds = 60; // Время, за которое считается счётчик, секунды
$limiterThreshold = 2; // Кол-во событий

// В данном случае 2 события в 60 сек.

// Проверяем счётчик
if ($this->limiter->tooManyAttempts($limiterKey, $limiterThreshold)) {
    throw new TooManyRequestsHttpException($decayIntervalInSeconds);
}

// Добавляем попытку
$this->limiter->hit($limiterKey, $decayIntervalInSeconds);

// ...  Делаем что-то

It is better to wrap it in some method or take it out to a service.

D
Daria Motorina, 2020-08-10
@glaphire

Here in the throttle dock, in theory, seconds are indicated
https://laravel.com/docs/7.x/middleware#middleware...
And here a hack is described in the issue, how to make seconds
https://github.com/GrahamCampbell/Laravel - Throttle...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question