What is the best way to take advantage of the database data for functions related to the recovered content?

Asked

Viewed 24 times

1

When I need to use a database information for more than one task, what is the best solution for object orientation( ex:list the products of a cart and perform calculations ):

1 - Create a single method that already does everything( 1 access to the bank and 1 while )

// recupera a lista de produtos do banco
$lista_produtos = $carrinho->listar_produtos();

// percorre os produtos e realiza as tarefas necessarias
while($carrinho_produto = $lista_produtos)
{
    $valor_produto = $carrinho_produto ->valor * $carrinho_produto ->quantidade;

    $valor_frete += $valor_produto * $fator_frete;`insira o código aqui`

    $valor_total += $valor_produto;
}

2 - Create 3 methods and list the products in each of them, consequently performing more access to the bank( 1 access to the bank by method and multiple while ).

$carrinho->calcular_preco();
$carrinho->calcular_frete();
$carrinho->calcular_valor_total();

3 - Retrieve the list of bank products, store in a vector, pass the vector in all methods( 1 access to the database and while multiples )

$vetor_produtos = $carrinho->listar_produtos();
$carrinho->calcular_preco( $vetor_produtos );
$carrinho->calcular_frete( $vetor_produtos );
$carrinho->calcular_valor_total( $vetor_produtos );

1 answer

0

Math,

the best option among those listed is the third, from the performance point of view (database queries are costly for performance), maintainability (each function performs a task, if an error occurs it will be clear where it comes from and therefore it will be easier to correct) and from a style point of view also, considering that your code is much more readable.

It is also important to consider whether these products will be modified by a single instance of their application, because otherwise you despite being working with information without needing a database query possibly will be working with a copy of the data that is not updated.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.