G
G
Glory2021-02-12 23:12:36
OOP
Glory, 2021-02-12 23:12:36

Is it possible to use the add. access to the database for the benefit of the beauty of the code?

I ask a question. When you write code, in the OOP style, but at the same time access the database, should you strive to reduce the number of calls to the database? For example, code:

static funtion ProductExists( $name ) {
    return  Product::where('name', $name)->exists();
}

static function blablabla( $data ) {
   if (Self::ProductExitst( $data['name'] ) {
        $id = Product:: where('name', $data['name'])->first()->id;
        ProductComment::where('product_id', $id ) .....
        ProductDocuments::....
   }
}

Or is it better not to call the ProductExists method, but immediately

$product = Product:: where ( 'name', $name)->first();
if ( $product ) {
             ProductComment::where('product_id', $product->id ) .....
}

In the first case, we first make a query to the model, followed by a query to the database.
then we essentially make a database request again to get the necessary data and already use it in the code.

In the second case, we immediately get the data (if any) and if they exist, then use them.

So you need a readable OOP style for cases like this? it improves readability, but increases the number of base calls.

Well, this is the simplest case, maybe not completely revealing the question. I want to know how to do Orthodoxy.

Tell me what and how

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-02-12
@AleksandrB

And what does OOP have to do with it? OOP does not tell us how often to query the database, what queries to write. OOP suggests working with objects. What's the deal with readability? I can read both several calls to the methods of accessing the database, and one.
Reducing the number of calls to the database is not an OOP approach. This is a performance optimization approach. If you have 1 request, your code will run faster than if there were 2 requests. Code readability is enhanced by good method design - separation of concerns, correct names, and more.
In this case, there is no point at all in making several identical requests. In yours, you will most likely just get an error if the element is not found in the database. If not, then checking is
if ( $product ) ...
enough.

A
Alexander Skusnov, 2021-02-13
@AlexSku

Ways to improve speed:
1) Stored procedures. (I don’t remember if such a method as including parameters has not touched the database for a long time). The number of procedures can be made any.
2) The sequence of joining tables (Join), when you first need to apply the most efficient filters (reducing selections)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question