i'm training SOLID/Architectures and trying to make an INSERT on my code, but its insert four times on DB. There's any error on my logic? I'm following Repositories/Service Pattern.
i think my service is executing two times, but i cant find the reason.
Repositorie Code
public function inserirEstoque($dadosPost)
{
if (empty($dadosPost)) {
return false;
}
$pdo = $this->dbConnection->conectar();
$sql = $pdo->prepare('INSERT INTO estoque (nomeProduto, descriptions, price, quantity)
VALUES (:nome, :descriptions, :price, :quantity)');
$sql->bindValue(':nome', $dadosPost['nomeProduto']);
$sql->bindValue(':descriptions', $dadosPost['descriptions']);
$sql->bindValue(':price', $dadosPost['price']);
$sql->bindValue(':quantity', $dadosPost['quantity']);
$res = $sql->execute();
if($res == false)
{
return false;
}
return $res;
}
Service
public function insertEstoque()
{
$db = new MySQL();
$insert = new EstoqueRepositories($db);
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
}
Controller
public function insert()
{
$insert = new EstoqueService();
$insert->insertEstoque();
header('Location: ../../index.php');
}
CodePudding user response:
It's executing twice because of this
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
if you wanna check if the POST data is empty just remove where it inserts the data then it should just insert it 1 time
if(!empty($_POST["whatevername"])){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
CodePudding user response:
As an addition to Reed's answer, if you just want to check the result of a function call before carrying on, assign the result to a variable and use that variable.
$res = $insert->inserirEstoque($_POST)
if(!empty($res)){
return $res;
} else {
return false;
}