extending PDO class

后端 未结 2 1905
孤城傲影
孤城傲影 2020-12-17 17:22

Below is the db connection class I came out with so far, but I am going to improve it by extending the PDO class itself,



        
相关标签:
2条回答
  • 2020-12-17 17:55

    $dsn is data source name. It handles your hostname for you. You use it like this:

    $dsn = 'mysql:dbname=YOUR_DB_NAME;host=YOUR_HOSTNAME'
    

    With the line $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); You have set exceptions to be raised when errors occur (which I like), so in your extended class you can handle errors in exception handlers. If you had a method called getAssoc in your extended PDO class then it would look like this:

    /// Get an associative array of results for the sql.
    public function getAssoc($sql, $params=array())
    {
       try
       {
          $stmt = $this->prepare($sql);
          $params = is_array($params) ? $params : array($params);
          $stmt->execute($params);
    
          return $stmt->fetchAll(PDO::FETCH_ASSOC);
       }
       catch (Exception $e)
       {
          // Echo the error or Re-throw it to catch it higher up where you have more
          // information on where it occurred in your program.
          // e.g echo 'Error: ' . $e->getMessage(); 
    
          throw new Exception(
                __METHOD__ . 'Exception Raised for sql: ' . var_export($sql, true) .
                ' Params: ' . var_export($params, true) .
                ' Error_Info: ' . var_export($this->errorInfo(), true),
                0,
                $e);
       }
    }
    
    0 讨论(0)
  • 2020-12-17 18:10

    I would concentrate on what the class needs to do rather than trying to re write the PDO. I had the same idea because i though it would simplify and stream line the code but it doesn't. You end up spending more time working out how to indirectly interface with the PDO.

    0 讨论(0)
提交回复
热议问题