A
A
AlpineMilk2020-09-01 21:13:38
PHP
AlpineMilk, 2020-09-01 21:13:38

When should you use the command bus?

Hello everyone,
When should I use commandBus? Should I use it for regular crud?
I'm using symphony and I like the forms component it provides.

public function new(Request $request): Response
    {
        $command = new CreateCurrencyCommand();
        $form = $this->createForm(CurrencyType::class, $command);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->commandBus->handle($command);

            return $this->redirectToRoute('admin_currency_index');
        }

        return $this->render('admin/currency/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

The content of the form is CreateCurrencyCommand(Normal DTO which contains fields and getters / setters) and the creation of a currency looks very good, a very thin controller and business logic is placed in a separate handler that creates an entity and saves it to the database.
The problem arose when I tried to do the same for editing, the main problem is the data for the form, since it is already used CreateCurrencyCommandinstead of UpdateCurrencyCommand. This is what the edit method looks like without command intervention
public function edit(Request $request, Currency $currency): Response
    {
        $form = $this->createForm(CurrencyType::class, $currency);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('admin_currency_index');
        }

        return $this->render('admin/currency/edit.html.twig', [
            'currency' => $currency,
            'form' => $form->createView(),
        ]);
    }


And here I see 2 options:
1. Make a universal command without division into creation / editing / deletion (if you do it this way, how is it better to arrange the command and handlers into folders?)
2. Make 2 forms for creating and editing and give for each my team, which somehow I don’t really want to do.
3. Do not use commands during crud operations.
This is the simplest example of entity creation. For this case, you can leave it as it is and the method will not be large, but not every creation looks so simple.
Advise on the best way to do it? And why? Maybe you should do it some other way that you know.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question