0
I have a small package manager in the terminal of own use and that manages my Framework, and I am giving an improvement on it, and falls into a problem where I can not loop without using goto, as in the code below:
$stdin = fopen('php://stdin', 'r');
$rs_add_deps = fgetc($stdin);
$requires = [];
if ($rs_add_deps == 's') {
add_req:
echo "Digite o pacote completo:";
$stdin = fopen('php://stdin', 'r');
$countReq = count($requires);
$requires[$countReq] = fgetc($stdin);
goto test_add_req;
} else {
end_add_req:
var_dump($requires);
}
test_add_req:
echo "Adicionar outro pacote?";
$stdin = fopen('php://stdin', 'r');
$add_n_pack = fgetc($stdin);
if ($add_n_pack == 's') {
goto add_req;
} else {
goto end_add_req;
}
This script adds possible packages to the array $requires[]
according to what the user defines that he wants, it works perfectly, knowing that the interaction is via terminal and that I will never know how many packages are and (he makes tests to know if the package is valid but I cleaned to be simpler example), there is a less crooked way to capture these values and add to the array?
Another second solution I have is this, but I found it much more complex than using the drip:
$stdin = fopen('php://stdin', 'r');
$rs_add_deps = fgetc($stdin);
$requires = [];
$countReq = 0;
$ask = false;
if ($rs_add_deps == 's') {
while (true) {
if (is_numeric($countReq) === 0) {
echo "Digite o pacote completo EX: 'gm/bv4fphp':";
$stdin = fopen('php://stdin', 'r');
$requires[$countReq] = fgetc($stdin);
$ask = true;
$countReq += 1;
} elseif (is_numeric($countReq) > 0) {
if ($ask == true) {
echo "Adicionar outro pacote?";
$stdin = fopen('php://stdin', 'r');
$add_n_pack = fgetc($stdin);
if ($add_n_pack == 's') {
$ask = false;
} else {
$countReq = 'get-out';
}
} else {
echo "Digite o pacote completo:";
$stdin = fopen('php://stdin', 'r');
$requires[$countReq] = fgetc($stdin);
$ask = true;
$countReq += 1;
}
} else {
var_dump($requires);
break;
}
}
}
NOTE: This project is structured, 0 orientation, I did not want to leave this context in this project.
Kind of use a
while(true)
and givebreak
when the entry is different froms
?– Woss
You can create functions. But considering that this script of yours is very simple, I see no problem in leaving as is, if it works. GOTO is not the devil :)
– bfavaretto
@Andersoncarloswoss I tried with while(true), but found more complex than before
– AnthraxisBR
I’ve decided to leave my contribution to an image :D
– Isac