简体   繁体   中英

Abstract class 'n Interface, specifically in PHP

This question is in continuation to my previous post located here .

Since there is no way to post code sample again without editing your original post, I am starting a new post. And also, this contains PHP code.

I am writing two classes, first is for opening and closing connection to the database, and the second is to provide various reusable functions for DB access.

Below is my PHP code for the Connection class:

<?php
/**
* DBConnection Base Class Definition
*/

/* Include dependency */
require_once("\config\dbconfig.php");

abstract class dbconnection 
{
 var $conn;
 //Opens connection for a MySQL DB
 abstract function OpenConnection()
 {
  $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
     or die($this->ShowError(mysql_error()));
  mysql_select_db(DB_NAME) or die ($this->ShowError("Connection to MySQL Database Failed. "));  
 }

 //Closes connection for a MySQL DB
 abstract function CloseConnection()
 {
  try
  {
   mysql_close($conn);
  }
  catch(exception $ex)
  {
   $this->ShowError($ex);
  }
 }

 protected function ShowError($err)
 {
  echo "<script>alert('Error: ' +". $err .");</script>"; 
 }  
}
?>

The file included in the above code contains following code:

<?php
//Modify constants with data needed to access your own database
define('DB_HOST','localhost:3306');
define('DB_NAME','MyStore');
define('DB_USER','super');
define('DB_PASSWORD','****');
?>

Now here are my queries related to abstract class and interfaces (continued from my previous post):

(1) Can a connection class be abstract? Are the methods written correctly?
(2) Instead of making the second code a file "dbconfig.php", will it be good to make an Interface for it?

I don't see any reason why you should mark this method as abstract. It is possible, but with what purpose? The methods should be defined without a body if declared abstract. If you want to force a way in connecting than you are better of with defining an interface and implementing it.

I't is not smart to define your db configs as constants in this way. You probably be better of by giving them as a parameter. That way you are more flexible in connecting with multiple db's for example.

(1a) yes

(1b) it seems so. But you shouldn't use die in OOP please use exceptions .

(2) In general it might be better OOP-style to use an interface. For PHP in this case it is totally ok to use constants. But this is strongly subjective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM