Php5 - classe de news et de commentaires


Contenu du snippet

Bonjour bonjour :)

Bon je tiens à rassurer tout le monde, aujourd'hui je fais quelque chose de pas bien nouveau. En faites, j'avais fait y'a longtemps une classe de news mais c'était pas génial génial. L'interfacage était pourris bref... je refais quelque chose de nouveau.

Au menu ?
Une classe d'abstraction pour gérer les méthodes de bases aux classes filles de news et de commentaires.
2 interfaces : une pour les news, l'autre pour les commentaires (juste pour uniformiser).
2 classes indépendantes :
- NewsObject
- CommentObject
1 classe fille qui hérite de mon abstraction pour les news.
1 autre classe fille pour les commentaires.

Voici donc le code (y'a rien de compliquer, alors j'ai pas pris la peine de le commenter pour le moment...) :

Source / Exemple :


<?php
class NewsObject {

 public $titre = NULL;
 public $resume = NULL;
 public $content = NULL;
 public $id = NULL;
 public $date = NULL;
 public $date_update = NULL;
 public $commCount = NULL;
 public $lastcomm = NULL;
 
 
 public function __construct($array=NULL) {
 	
  if ( is_array($array) ) {
  	   foreach ($array as $key=>$val ) {
  	   	        if ( property_exists($this, $key) ) $this->$key = $val;
  	   }   
  }
 
  $this->id = (int) $this->id;
 }	
 
 
 public function CheckFields() {
  if ( !isset($this->titre) )   throw new Exception ('Le champ titre n\'est pas rempli !');
  if ( !isset($this->content) ) throw new Exception ('Le champ contenu n\'est pas rempli !');
 }

}

class CommentObject {
	
 public $login = NULL;
 public $id = NULL;
 public $date = NULL;
 public $content = NULL;
 
 public function __construct($array=NULL) {
 	
  if ( is_array($array) ) {
  	   foreach ($array as $key=>$val ) {
  	   	        if ( property_exists($this, $key) ) $this->$key = $val;
  	   }   
  }
 
  $this->id = (int) $this->id;
 }	
 
}

interface iNews {
 public function GetUniqueNews($newsID);
 public function GetMultipleNews($start, $limit);
 public function GetNextNewsID();
 public function CountAllNews();
 public function AddNews( NewsObject $objet);
 public function DeleteNews($newsID); 
 public function UpdateNews( NewsObject $objet);  
}

interface iComment {
 public function GetCommentsFromNewsID( NewsObject $objet );
 public function DeleteComment($commentID);
}

abstract class Factory {
 protected $db;
 protected $_option = array(
              'outputMethod' => 'ToObject');
 public $flag = FALSE;	
 protected $childname;
	
 public function __construct() {
  $this->db = mysql::GetInstance();	
 }
 
 public function SetOutputMethod($methodname) {
 	
  switch ( strtolower($methodname) ) {
  	case 'object' :
  		  $this->_option['outputMethod'] = 'ToObject';
  		  break;
  	case 'xml' :
  		  $this->_option['outputMethod'] = 'ToXML';
  		  break;
  	default :
  		  throw new Exception($methodname.' n\'est pas reconnu en tant que méthode de sortie !');
  }
 	
 }
 
 abstract protected function ToObject($array);
 abstract protected function ToXML($array);
 
}

class NewsFactory extends Factory implements iNews {
  	
 public function __construct() {	
  parent::__construct(); 	
 }
 
 public function GetUniqueNews($newsID) {
 	
  $this->db->prepare('SELECT
                       id, titre, content, resume,
                       DATE_FORMAT(date,"%d-%m-%Y à %Hh%i") as date,
                       DATE_FORMAT(dateupdate,"%d-%m-%Y à %Hh%i") as date_update
                      FROM
                       news
                      WHERE
                       id = {1}',
                      (int) $newsID);
  $this->db->query();
  return $this->{$this->_option['outputMethod']}( $this->db->fetch_array() );
   	
 }

 public function GetMultipleNews($start, $limit) {
 	
   if ( !$this->flag ) {
         $this->db->prepare('SELECT
   		        	          news.id, news.titre, news.resume, news.content,
   		          		      DATE_FORMAT(news.date,"%d-%m-%Y à %Hh%i") as date,
   		           		      DATE_FORMAT(news.dateupdate,"%d-%m-%Y à %Hh%i") as date_update,
   		           		      COUNT(commentaires.id) as commCount,
   		            		  DATE_FORMAT( MAX(commentaires.date), "%d/%m/%Y") as lastcomm
   		            	     FROM
   		            		  news
   		           			 LEFT JOIN
   		               		  commentaires ON news.id = commentaires.id_news
   		             		 GROUP BY
   		                      news.id
   		             	     ORDER BY
   		             		  news.id DESC
   		             	     LIMIT {1}, {2}',
	                 		  (int) $start, (int) $limit); 	 
        $this->db->query();
        $this->flag = TRUE;
   }
  
  return $this->{$this->_option['outputMethod']}( $this->db->fetch_array() );
 	
 	
 }
 
 public function GetNextNewsID() {
 
  $this->db->query('SELECT MAX(id) + 1 FROM news');
  $data = $this->db->fetch_row();
  return ( (int) $data[0] );
  
 }
 
 
 public function AddNews( NewsObject $objet) {

  $objet->CheckFields();
   
  $this->db->prepare("INSERT INTO news (titre, resume, content, date) VALUES ('{1}', '{2}', '{3}', NOW() )",
                      $objet->titre, $objet->resume, $objet->content);
  $this->db->query();	
  
   if ( $this->db->affected_rows() === 1 ) {       
		return $this->db->insert_id();
   } else {
        return false;
   }
   	
 }
 
 public function DeleteNews($newsID) {
  
  $this->db->prepare('DELETE FROM news WHERE id = {1}', (int) $newsID);
  $this->db->query();	
  
  return ( $this->db->affected_rows() === 1 ) ? TRUE : FALSE;
  
 }
 
 public function UpdateNews( NewsObject $objet) {

  $objet->CheckFields();
  
  $this->db->prepare("UPDATE news SET content = '{1}', resume = '{2}', titre = '{3}' WHERE id = {4}",
                    $objet->content, $objet->resume, $objet->titre, $objet->id);
  $this->db->query();	
  
  return ( $this->db->affected_rows() === 1 ) ? TRUE : FALSE;       
   	
 }
 
 public function CountAllNews() {
 	
  $this->db->query('SELECT COUNT(id) FROM news');
  $this->db->query();

  $data = $this->db->fetch_row();
  return ( (int) $data[0] );
    	
 }
 
 protected function ToObject($array) { 
 	
   if ( $array === FALSE ) {
   	    $this->flag = FALSE;
   	    return FALSE;
   } else {
   	    return new NewsObject($array);
   }
	
 }
 
 protected function ToXML($array) {

   if ( $array === FALSE ) {
   	    $this->flag = FALSE;    
   	    return FALSE;	
   }
 
  $doc = new DOMDocument('1.0');
  $root = $doc->CreateElement('news');
  
   foreach ( $array as $key=>$val ) {
             $newElem = $doc->createElement($key, $val);
             $root->appendChild($newElem);      
   }
   
  $doc->appendChild($root);
  
  return $doc->saveHTML();
  
 }
 
}

class CommentFactory extends Factory implements iComment {
	
 public function __construct() {
  parent::__construct();
 }

 public function GetCommentsFromNewsID( NewsObject $objet ) {
 	
  $this->db->prepare("SELECT
                       id, login, content, date, ip
                      FROM
                       commentaires
                      WHERE
                       id_news = {1}",
                      (int) $objet->id);
 $this->db->query();

 return $this->{$this->_option['outputMethod']}( $this->db->fetch_array() );
 	
 }
 
 public function DeleteComment($commentID) {
  
  $this->db->prepare('DELETE FROM commentaires WHERE id = {1}', (int) $commentID);
  $this->db->query();	
  
  return ( $this->db->affected_rows() === 1 ) ? TRUE : FALSE;
  
 }
 
 protected function ToObject($array) { 
 	
   if ( $array === FALSE ) {
   	    $this->flag = FALSE;
   	    return FALSE;
   } else {
   	    return new CommentObject($array);
   }
	
 }
 
 protected function ToXML($array) {

   if ( $array === FALSE ) {
   	    $this->flag = FALSE;    
   	    return FALSE;	
   }
 
  $doc = new DOMDocument('1.0');
  $root = $doc->CreateElement('comment');
  
   foreach ( $array as $key=>$val ) {
             $newElem = $doc->createElement($key, $val);
             $root->appendChild($newElem);      
   }
   
  $doc->appendChild($root);
  
  return $doc->saveHTML();
  
 }
 
}
?>

Conclusion :


Vous allez me dire, l'est gentil... mais ca marche comment ?
Alors voila :
<?php
try {
$NewsFactory = new NewsFactory;

$news = $NewsFactory->GetUniqueNews( (int) $_GET['id'] ); // Imaginons qu'on récupère l'ID d'une news via un GET.
echo $news->id;
echo $news->titre;
echo $news->content;
// etc...
} catch ( Exception $e ) { // Sait on jamais !
echo $e->getMessage();
}
?>

Pareil pour les commentaires !
C'est ultra simple, ultra modulaire, et ca peut s'intégrer partout !
Si vous voulez une sortie XML, il suffit de le spécifier via : public function SetOutputMethod($methodname);

Toujours aussi compliqué ? Mais non... allez suffit de fouiller un peu =)

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.