Practicing Creating DB classes, need a little guid

2019-09-02 20:31发布

So I am on a mission to learn how to create DB classes of my own using PDO. I am fairly new to PDO and more complex class development and wanted to get a little guidance from the community before I get too far into it. I have a class partially built but I know there has to be a better/more logical way to do this.

I'd really like to be able to have a single query method so I can trow almost anything at it in my DB class. If this is faulty thinking please let me know why.

Currently I have a config.php file with DB constants defined and a class called DB. Here's my Code:

In index.php:

    require_once 'config.php';      
    require_once '_inc/class.db.php';
    $db = new DB();

And my class:

        public $dbh;


public function __construct(){

    $dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);

}//end __construct


public function build_query( $args ){

    $defaults = array(
                      'type' => 'SELECT',
                      'fields' => '*',
                      'table' => '',
                      'where' => '',
                      'orderby' => 'id',
                      'order' => 'DESC'
                      'offset' => '0',
                      'limit' => ''
                      );

    $params = array_merge( $defaults, $args );

    $sql = $params['type'];

    $sql .= ' '.$params['fields'].' FROM '.$params['table'];

    if( $params['where'] )
        $sql .= ' WHERE '.$params['where'];

    $sql .= ' ORDER BY '$params['orderby'].' '.$params['order'];

    if( $limit )
        $sql .= ' LIMIT '.$params['offset'].', '.$params['offset'];

    return $sql;    

}//end build_query


public function dbq( $args ){

    $sql = $this->build_query( $args );

    $this->$dbh->prepare( $sql );

    return $this->$dbh->execute();

I know I am missing something here. Please just push me in the right direction as I really want to learn this to become a better PHP developer. I did look a little at using singleton pattern but wanted to get a little more info from people who really know how it all works and fits together.

Thanks in advance!

标签: php class pdo
1条回答
一夜七次
2楼-- · 2019-09-02 21:14

If I read your question right, you are looking for a so called Query-Builder. A query builder is a class that has some parameters and which can return the query based on the parameters.

Actually this needs nothing more and nothing less if the example you have above is what you need. You only need to put that into a class of it's own because the rest of the database layer has other things to do.

You can then pass the Query object to where it belongs to. Normally you use that internally in some class. So you are actually not asking about creating a general DB god class (which would be a smell btw), but you just want to wrap the SQL Query String Builder into a class of it's own:

/**
 * SQL Query
 */
class SqlQuery
{
    public
        $type = 'SELECT',
        $fields = '*',
        $table,
        $where,
        $orderby = 'id',
        $order = 'DESC',
        $offset,
        $limit;

    /**
     * @return string
     */
    public function getQuery() {

        $sql = sprintf('%s %s FROM %s', $this->type, $this->fields, $this->table);

        $this->where
            && $sql .= sprintf(' WHERE %s', $this->where)
        ;

        $sql .= sprintf(' ORDER BY %s %s', $this->orderby, $this->order);

        $this->limit
            && $sql .= sprintf(' LIMIT %s, %s', $this->offset, $this->limit)
        ;

        $sql .= ';'; ### not strictly necessary but nice for debugging ###

        return $sql;
    }

    public function __toString() {
        return $this->getQuery();
    }
}

### Usage: ###

$query = new SqlQuery;
$query->table = 'TABLE1';
echo $query; // SELECT * FROM TABLE1 ORDER BY id DESC;

This example actually covers everything you have so far but gives it a defined interface. So you have the default property values and you have the build function. You can then pass that SqlQuery around where you need it.

查看更多
登录 后发表回答