Dry and similar requests

Working on a specific application, I continue to write very similar queries over and over again. They are not exactly the same, but they have a very similar shape and are embedded in almost identical pieces of code, for example,

$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT foo 
                              FROM tblFoo 
                              WHERE something = ?")) {
    $Stmt->bind_param('s', $this->_something);
    $Stmt->execute();
    if (0 != $Stmt->errno)
        throw new Exception("blah, blah, blah");
    $Stmt->bind_result($foo);
    while ($Stmt->fetch()){
        $this->_foos[] = new Foo($foo);
    }
    $Stmt->close();
    } else {
        throw new Exception("blah, blah, blah"););
    }
}

and then, somewhere else ...

$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT bar, baz 
                              FROM tblBar 
                              WHERE somethingElse = ?")) {
    $Stmt->bind_param('s', $this->_somethingElse);
    $Stmt->execute();
    if (0 != $Stmt->errno)
        throw new Exception("blah, blah, blah");
    $Stmt->bind_result($bar, $baz);
    while ($Stmt->fetch()){
        // do something else with $bar and $baz
    }
    $Stmt->close();
    } else {
        throw new Exception("blah, blah, blah"););
    }
}

... and then another, and in another place another, etc.

Is this a real violation of DRY? It seems there is no point in writing a class to perform this kind of query (with constructor parameters or setters for a table, column, related variables, etc.), and then reusing it throughout the application. But at the same time I cannot shake this picky feeling that I am repeating myself.

Maybe there are just so many ways to write a simple query and that a certain number of repetitions like this are expected.

Thoughts?

+3
3

. , , . . , , . .

, hibernate, .

+1

, . ( - ) , "foo" "bar" ( ) -.

, . , SQL, , . - . SQL, .., ?

( - )

, , -, "" ( , ).

, .

(PS . , "" )

+1

.: -)

. - ( ) . . . . , , : , , , . DAL, . .

- , ( , -, SQL). , , ORM, DAL. .

0

Source: https://habr.com/ru/post/1703934/


All Articles