5

I am building a plugin for Shopware 6 and cannot seem to find any documentation as to how to extend an existing controller action. I found this How to add an Action to Account Controller in Shopware but it seems to refer to Shopware 5 and I am not sure I can use it that way in Shopware 6.

The controller action I want to extend is \Shopware\Storefront\Controller\AddressController::saveAddress - in my case I want to add custom address validation that would use a service in my plugin where a request to 3rd party API would be made, if the address is correct then allow the address, if not then return an error. Perhaps it is better to instead extend \Shopware\Core\Checkout\Customer\SalesChannel\AddressService::save but I have no clue for now (I am new to Shopware in general). Extending the service would mean I do not have to override the whole action logic so that it contains my check in the middle. Or perhaps there is an event I can use for address saving (same thing, can't find a good source/list of events for Shopware6).

There seem to be guides here: https://docs.shopware.com/en/shopware-platform-dev-en/developer-guide/controller and here: https://docs.shopware.com/en/shopware-platform-dev-en/how-to/custom-storefront-controller but these only describe how to make a new controller and it is not very useful to me since I do not want to add any new routes but use the existing one /account/address/create.

I would be very grateful for a code example of how to register the override in the plugin (config, xml) and how would the extending class look like. If it is not too much to ask the ideal answer would contain an example of:

  1. How to extend an action for existing controller.
  2. How to extend an existing service.
  3. Where to find which event is firing in a controller/service, subscribe to it and make it override default behaviour (like throw Shopware\Core\Framework\Validation\Exception\ConstraintViolationException).
4

1 回答 1

4
  1. It does not make sense to extend/override action, as action should be as thin as it is possible, and all business logic should be in service.

  2. To extend existing service you can decorate it or subscribe to some events to extend functionality. See https://docs.shopware.com/en/shopware-platform-dev-en/how-to/decorating-a-service

  3. In your case, you can subscribe on framework.validation.address.create or/and framework.validation.address.update events to extend list of constraints. In general all validation events have prefix framework.validation. second part is defined in \Shopware\Core\Framework\Validation\DataValidationFactoryInterface implementation in your case it is \Shopware\Core\Checkout\Customer\Validation\AddressValidationFactory

于 2020-08-05T09:59:41.320 回答