I have 10 actions in one Controller. Every action required ID from request. I want to check ID in constructor for every action, so I want avoid to write the same code 10 times in every action.
obviously, In constructor I can not use functions like:
$this->params()->fromQuery('paramname'); or
$this->params()->fromRoute('paramname');
So, the question is how to get request params in controller's constructor?
Short answer: you cannot. The plugins (you are using
params
here) are available after construct, unfortunately.There are two ways to make your code DRY: extract a method and perform extraction with the event system.
Extract method: the most simple one:
Or if you want to hydrate the parameter directly, this is how I do this quite often:
With the event sytem: you hook into the dispatch event to grab the id and set it prior to execution of the action:
This feature works as upon dispatch, the loadId() method is executed and then the other (fooAction/barAction) method is ran.