I have an action that does two things:
- It sends a chain of commands, and gets the response from an external API that we call
wrapper
. - It logs the chain of commands and the tunnel (look at tunnels as different machines) the command was sent to.
My problem is the contents of the if
statement. The two things (sending the command/getting the response, and logging the exchange) are happening in that if
block, and they both need the chain
and tunnel
variables. I'd ideally want to have two functions, getResponseFromWrapper()
and logCommandAndResponse()
, effectively reducing the number of statements inside my if
block to just two.
public function indexAction(Request $request)
{
$response = '';
$form = $this->createForm(new TerminalType());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$tunnel = $data['tunnel'];
$chain = $data['chain'];
$response = $this->retrieveResponseFromWrapper($chain, $tunnel);
$this->get('command_logger')->log($chain, $tunnel, $response);
}
return $this->render('terminal/index.html.twig', [
'title' => 'Terminal',
'form' => $form->createView(),
'response' => $response
]);
}
In other words, I feel like the three first lines in the if
block are making it a bit more difficult for the reader to know what's happening.
Better code might be:
public function indexAction(Request $request)
{
$response = '';
$form = $this->createForm(new TerminalType());
$form->handleRequest($request);
if ($form->isValid()) {
list($chain, $tunnel) = $this->extractChainAndTunnelFromForm($form);
$response = $this->retrieveResponseFromWrapper($chain, $tunnel);
$this->get('command_logger')->log($chain, $tunnel, $response);
}
return $this->render('terminal/index.html.twig', [
'title' => 'Terminal',
'form' => $form->createView(),
'response' => $response
]);
}
This is much shorter. However, returning two values from a function leaves a bad taste in my mouth.
How can I improve the first code block and reduce the number of statements in the if
block? Do I need to create something like a DTO
(i.e. have my extractCommandAndTunnelFromForm()
create a plain old PHP object and set the tunnel
and chain
as its properties)? Do I need to inject the commandLogger
service into the service that sends commands to the wrapper
, and remove logging from the controller entirely?