Good.
I have the following code:
<?php
class ControladorDeEjemplo extends Controller
{
public function store(StoreData $request)
{
$data = $request->all();
/*
bloque de
instrucciones
bastante extenso 1
*/
if ($condicionDeError) {
return response()->json(['success' => false, 'error' => 'Descripcion del error']);
}
/*
bloque de
instrucciones
bastante extenso 2
*/
return response()->json(['success' => true]);
}
}
and I want to output the statement block to another function, since the original method I want to fix is over 120 lines long. So I want to do something like this:
<?php
class ControladorDeEjemplo extends Controller
{
public function store(StoreData $request)
{
$data = $request->all();
funcion($data);
/*
bloque de
instrucciones
bastante extenso 1
*/
return response()->json(['success' => true]);
}
public public function Funcion($datos)
{
/*
bloque de
instrucciones
bastante extenso 2
*/
$variable1;
$variable2;
if ($condicionDeError) {
return response()->json(['success' => false, 'error' => 'Descripcion del error']);
}
}
}
But some problems I have are:
The first block of instructions consults the database and assigns the variables necessary for the
/* bloque de instrucciones bastante extenso 2 */
function to work (which in this example would be the$variable1
and$variable2
)If it is not used
return
when the function is calledFuncion()
insidestore()
, it does not return the error, but if it is used, it does not continue the routine to the end, even if the conditions are correct.
This can be fixed with a condition like this. (this is an idea)
<?php
if(get_class($result = funcion()) == "Response"){
return $result;
}
But I have no way to pass the results of the function to the previous "store" context without making them variables of the class.
Another idea is to use exceptions and return the data as arrays. As indicated by http-exceptions . But this involves modifying the code that interprets the output in javascript.
I would like to know if there is a way to do this elegantly :P
You would not handle the exceptions in the frontend but directly in PHP. From what I read, I understand that $variable1 and $variable2 are generated in
Funcion
and you need to return them. In that case it would beIf the operation you perform in Function does not throw an exception natively, then you can add, prior to return:
And with that you would trigger the catch of your store function.