Hace poco empecé a programar con objetos y estoy haciendo un pequeño blog. Me gustaría saber si lo que estoy haciendo esta bien, saber que tengo que correjir y demas.
Este es lo que hice:
config.php
Código PHP:
<?php
define("HTTP_HOST", $_SERVER['HTTP_HOST']);
if (HTTP_HOST == "www[dot]misitio[dot]com" || HTTP_HOST == "misitio[dot]com") {
$dbHost = 'misitio[dot]com';
$dbUser = 'user';
$dbPass = 'pass';
$dbName = 'dbname';
} else {
$dbHost = 'localhost';
$dbUser = 'local_user';
$dbPass = 'local_pass';
$dbName = 'local_dbname';
}
?>
Código PHP:
<?php
class ConfigDataBase {
private $_dbHost;
private $_dbUser;
private $_dbPass;
private $_dbName;
public function __construct() {
require 'includes/config.php';
$this->_dbHost = $dbHost;
$this->_dbUser = $dbUser;
$this->_dbPass = $dbPass;
$this->_dbName = $dbName;
}
private function __clone() {}
public function getHostDB() {
$var = $this->_dbHost;
return $var;
}
public function getUserDB() {
$var = $this->_dbUser;
return $var;
}
public function getPassDB() {
$var = $this->_dbPass;
return $var;
}
public function getNameDB() {
$var = $this->_dbName;
return $var;
}
}
class ConnectionDataBase {
private $dbHost;
private $dbUser;
private $dbPass;
private $dbName;
private $link;
private $result;
function __construct() {
$this->configConnection();
$this->setConnection();
}
protected function configConnection() {
$config = new ConfigDataBase();
$this->dbHost = $config->getHostDB();
$this->dbUser = $config->getUserDB();
$this->dbPass = $config->getPassDB();
$this->dbName = $config->getNameDB();
}
private function __clone() {}
private function setConnection() {
$this->link = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
if ($this->link)
mysql_select_db($this->dbName);
else
throw new Exception('Database Error No. ' . mysql_errno() . ': ' . mysql_error());
}
function __destruct() {
mysql_close($this->link);
}
}
?>
¿Conviene hacer la conexion aca adentro o es mejor hacerla en el index.php (mas abajo) y despues instanciar cla clase Post?
Código PHP:
<?php
class Post {
private $link;
private $query;
private $result;
function __construct() {
$this->setConnection();
}
protected function setConnection() {
require_once 'app/connection.class.php';
$this->link = new ConnectionDataBase();
}
public function getList($totalRow, $orderBy) {
$this->query = "SELECT * FROM post WHERE status = 'A' ORDER BY " . $orderBy . " DESC LIMIT 0," . $totalRow;
$this->result = mysql_query($this->query);
return $this->result;
}
public function getPostById($id) {
$this->query = "SELECT * FROM post WHERE status = 'A' AND id = " . $id;
$this->result = mysql_query($this->query);
return $this->result;
}
}
?>
Código PHP:
<?php
require_once 'app/post.class.php';
$posts = new Post();
$post = $posts->getList(10, 'date');
while ($p = mysql_fetch_object($post)) {
echo '<div style="margin-bottom: 5px;"><a href="view-post.php? id_post='.$p->id.'" title="">'.$p->title.'</a></div>';
}
mysql_free_result($post);
?>
Saludos !