Applying SRP causing problems. How to?

60 views Asked by At

I am creating my own Query Builder using php which can also execute queries and get results from the database. At first I had this functionality within one class, however after thinking it through I believe the QueryBuilder and the DBProcessor should be two separate classes.

class QueryBuilder {

    var $query;

    ...
    function select()
    function from()
    function join()
    function where()
    ...
}

class DbProcessor {

    ...
    function execute()
    function rowCount()
    function startTransaction()
    function lastInsertId()
    ...
}

The problem I am having is using thse together whilst trying to stick to other good programming conventions.(loose coupling)

Should I create a construct within the QueryBuilder so that a instance of DbProcessor must be passed in upon creation? However this idea it seems to go downhill as I would end up duplicating method names inside my QueryBuilder just to call methods within DbProcessor kind of like the following

class QueryBuilder {

    var $DbProcessor;

    function select()
    ...

    function rowCount() 
    {
        $this->DbProcessor->rowCount()
    }

    function startTransaction() 
    {
        $this->DbProcessor->startTransaction()
    }
}

This way just seems to add duplicate method names and making it seem better to just put the DbProcessor inside QueryBuilder.

How can I achieve what I want here?

1

There are 1 answers

0
korima On

I have done something similar in a personal project. In my case, your QueryBuilder, is only responsible for building sql statements returning a String var. No executions. Only fabric a pure string SQL. In the other hand, database, has a method to execute the SQL sentence that is passed as argument. Then, to orchestrate the entire query execution, I have other class, xxxRepository.java where I will have all entities methods of the kind of getXXXById(). This calls to QueryBuilder.java returning the SQL what I want to execute and then I passed it to Database.java execute() method to get results.