简体   繁体   中英

Symfony validation. API Resource validation custom logic

I want to write base validator. It is possible to catch "pre validation" event for Entity? If it possible I'll call ValidatorInterface with current entity dynamic constraints. It's my own researching, I only study :)

There is no such event 'pre validation' in symfony, but you can dispatch your own event using EventDispatcher from whenever you want, and handle them in EventListener or EventSubscriber.

But i suppose you not to run validator on entity at all. Entity is a domain term, try to avoid infrastructure code in them. And input validation is an example of such "infrastructure" code. Consider creation of another class, like InputDto, which will be mapped directly from request and then validated using validator (possibly in several stages: you can run one validation groups, than convert some values, than run next validation groups and so on). Then create entity by passing valid data from DTO to entity constructor.

Such approach will guarantee that if entity was created, it is in valid state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM