• Час читання ~4 хв
  • 07.04.2023

Запити форм найбільш відомі тим, що переміщують логіку перевірки з веб-контролерів у клас, який попередньо перевірятиметься для вас. Вони фантастичні, і я весь час сильно на них спираюся. Але що ще можна зробити із запитами на форми?

Окрім додавання методів і виклику їх у контролерах, є кілька методів, які часто не використовуються у ваших запитах форми, на які ви можете спиратися, щоб додати додаткові надздібності до своєї програми.

Підготовка вхідних даних до перевірки

Цей метод фантастичний, коли ви повинні трансформувати або додати більше до запиту до запуску валідатора. Документи показують приклад злиття в слимаку з чимось, що корисно, але як щодо іншого прикладу?

protected function prepareForValidation(): void
{
    $this->merge([
        'locale' => $this->user()->locale,
    ]);
}

We are merging the authenticated users' locale into the request - so we may perform dynamic validation based on the users' locale. Let's say we have limits in place in our application right now, which means that users from Wales (where I live) must add things in a specific format. Random, but I have seen a few use cases as a developer where this might have been useful.

Ми могли б навіть динамічно замінити вміст у цьому методі.

protected function prepareInputForValidation(): void
{
    $replace = match ($this->user()->locale) {
        'en_GB' => 17.5,
        'en_US' => 10.0,
        'de_DE' => 12.5,
    };
    $this->replace([
        'tax_percentage' => $replace,
    ]);
}

Here, we dynamically change the tax percentage based on the users' locale. This is useful if you have specific tax rates as part of your import tax as a distributor.

Пройдена

перевірка Подібно до підготовки до перевірки, ми можемо використовувати дані після перевірки, стандартизувати або форматувати дані запиту в певний формат. Як людина, яка щодня працює з даними, це дуже корисно.

protected function passedValidation(): void
{
    $this->replace([
        'name' => Str::uppercase($this->name),
    ]);
}

Again, these are not the most useful examples - but there is a lot you could do if you wanted, from turning properties into Value Objects for working with money to checking the content for spam.

Невдала авторизація Зазвичай, коли запит форми не вдається авторизувати

, фреймворк AuthorizationExceptionкидає файл . Для 99% випадків використання це все, що вам потрібно. Однак є ще кілька незрозумілих випадків, коли ви хочете уникнути такого винятку. Скажімо, ви захоплюєте веб-хуки зі стороннього API, і якщо ви кинете виняток авторизації, це створить дивну, неконтрольовану поведінку в цій третій стороні. Натомість ви можете тихо зазнати невдачі, перевизначивши цей метод у своєму запиті форми.

protected function failedAuthorization(): void
{
    Log::info('Failed authorization for webhook capture ....');
}

These are just a handful of the methods available on a Form Request, not to mention all those available using Laravel Precognition. But as I mentioned earlier, we can add our methods - allowing us to extend the functionality of our Form Requests a little more. A perfect example is the Laravel Breeze source code, where an authenticate method is added to the LoginRequest so the controller code can be simplified further.

Давайте розглянемо приклад контролера, який я зазвичай можу написати:

final class StoreController
{
    public function __construct(
        private readonly StoreCommand $command,
    ) {}
    public function __invoke(StoreRequest $request): Responsable
    {
        try {
            $this->command->handle(
                instance: new Instance(
                    name: $request->string('name')->toString(),
                ),
            );
        } catch (Throwable $exception) {
            throw new FailedToCreateInstance(
                message: 'Failed to create a new instance.',
                previous: $exception,
            );
        }
        return new CreatedResponse();
    }
}

This is a simplified controller where I use a creative class to send through a Data Object to keep my code consistent and clean how I like it. We can simplify our code more by leaning on our form request.

final class StoreController
{
    public function __construct(
        private readonly StoreCommand $command,
    ) {}
    public function __invoke(StoreRequest $request): Responsable
    {
        try {
            $this->command->handle(
                instance: $request->dto(),
            );
        } catch (Throwable $exception) {
            throw new FailedToCreateInstance(
                message: 'Failed to create a new instance.',
                previous: $exception,
            );
        }
        return new CreatedResponse();
    }
}

This looks similar, but imagine we are building something ten times more complex with many more request fields that we need to map to our data object - our controller will get big and messy in no time. All we have done here is move the creation of our Data Object to a method on the form request - nothing technical at all.

Межі того, що ви можете робити з вашими запитами форми, обмежені лише вашою фантазією, але переконайтеся, що ви використовуєте їх розумно. Вони існують не для того, щоб замінити логіку вашої програми, пам'ятайте! Важливо переконатися, що логіка вашої програми завжди доступна та читабельна, а також не загублена в морі фреймворкової логіки або перевірки запиту.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Про автора CrazyBoy49z
WORK EXPERIENCE
Контакти
Ukraine, Lutsk
+380979856297