IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

[POO] acces a certaines valeurs depuis ma classe


Sujet :

Langage PHP

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 211
    Points : 196
    Points
    196
    Par défaut [POO] acces a certaines valeurs depuis ma classe
    Bonjour,

    Je suis un peu débutant en matiere de POO, et j'ai besoin d'un petit peu d'aide.
    Ma classe peut en intéresser certains de toute facon. Le but est d'afficher un tableau avec possibilité de tri et de pagination a partir d'une requete SQL.

    Voici la classe:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
     
    <?php
    class dataTable {
    	function dataTable($sql,$conn='')
    	{
    		if ( empty($conn) )
    		{
    			global $connection;
    			$conn = $connection;
    		}
    		$this->sql = $sql;
    		$this->connection = $conn;
    		$this->fields = array();
    		$this->order = false;
    		$this->data = false;
    		$this->tr_function = false;
    		$this->num_records = 0;
    	}
    	function processRequest()
    	{
    		$this->limit = 100;
    		if ( isset($_GET['page']) )
    		{
    			$this->page = $_GET['page'];
    		}
    		else
    		{
    			$this->page = 1;
    		}
    		if ( isset($_GET['order']) )
    		{
    			$this->order = $this->fields[$_GET['order']]['name'];
    		}
    		else if ( $this->default_order )
    		{
    			$this->order = $this->default_order;
    		}
    		$order = $this->order ? ' ORDER BY '.$this->order : '';
    		$this->start = ( $this->page - 1 ) * $this->limit;
    		$req_num = mysql_query($this->sql,$this->connection) or die(mysql_error($this->connection).'<br />'.$this->sql);
    		$this->num_records = @mysql_num_rows($req_num);
    		$sql = $this->sql.$order.' LIMIT '.$this->start.','.$this->limit;
    		$req = mysql_query($sql,$this->connection) or die(mysql_error($this->connection).'<br />'.$sql);
    		$this->remain = $this->num_records % $this->limit;
    		$this->num_pages = ceil($this->num_records/$this->limit);
    		if ( $this->num_records > 0 )
    		{
    			$this->data = array();
    			while ( $data = mysql_fetch_array($req) )
    			{
    				array_push($this->data,$data);
    			}
    		}
    	}
    	function displayPagination()
    	{
    		global $query_string;
    		$res = '';
    		if ( $this->num_records > $this->limit )
    		{
    			if ( $this->num_pages > 1 )
    			{
    				$i = 1;
    				$res .= '<strong>Pages:</strong> &nbsp;';
    				while ( $i <= $this->num_pages )
    				{
    					if ( $this->page == $i )
    					{
    						$res .= '['.$i.']&nbsp;';
    					}
    					else
    					{
    						$res .= '<a href="'.$_SERVER['PHP_SELF'].$query_string.'page='.$i.'">'.$i.'</a>&nbsp;';
    					}
    					$i++;
    				}
    			}
    		}
    		return $res;
    	}
    	function displayTable()
    	{
    		global $query_string;
    		$table = '';
    		if ( $this->data && count($this->fields) > 0 )
    		{
    			$table .= '<table width="100%" cellpadding="3" cellspacing="0" border="0"><tr>';
    			foreach ( $this->fields as $key => $field )
    			{
    				$table .= '<td style="text-decoration:underline;';
    				if ( isset($field['dimension']) && !empty($field['dimension']) )
    				{
    					$table .= ' width:'.$field['dimension'].';';
    				}
    				$table .= '">
    					<a href="'.$_SERVER['PHP_SELF'].$query_string.'order='.$key.'"><strong>'.$field['title'].'</strong></a>
    				</td>';
    			}
    			$table .= '</tr>';
    			foreach ( $this->data as $data )
    			{
    				$table .= '<tr onmouseover="over(this);" onmouseout="out(this);"';
    				if ( $this->tr_function )
    				{
    					$table .= ' onclick="'.str_replace('"','\"',$this->tr_function).'"';
    				}
    				$table .= '>';
    				foreach ( $this->fields as $field )
    				{
    					$table .= '<td>';
    					if ( isset($field['datafunc']) && !empty($field['datafunc']) )
    					{
    						$table .= call_user_func($field['datafunc'],$data[$field['name']]);
    					}
    					else
    					{
    						$table .= $data[$field['name']];
    					}
    					$table .= ' </td>';
    				}
    				$table .= '</tr>';
    			}
    		}
    		else
    		{
    			$table .= <<<END
    			<table cellpadding="10" cellspacing="0" width="100%">
    				<tr>
    					<td>No record found.</td>
    				</tr>
    			</table>
    END;
    		}
    		return $table;
    	}
    }
    ?>
    Et voici comment je l'utilise:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
     
    // First I get 2 arrays, one for with the apps (appid=>appname) and one for the users (id=>username)
    $apps = getAppsAsArray();
    $users = getUsersAsArray();
    $apps[0] = 'Unknown';
    $users[0] = 'Application';
    // Then I create small functions to display the value corresponding to the ID
    // I would normally have done a JOIN in my SQL, but here the tables are on a different host
    function displayApp($id){
    global $apps;
    return $apps[$id];
    }
    function displayUser($id){
    global $users;
    return $users[$id];
    }
    // My SQL statement which will return all my results (do not put a limit)
    $sql = sprintf("SELECT msisdn,date,appID,comment,createdBy
    				FROM EndUserHistoryDev.Events
    				WHERE type = 'Note'
    				AND date BETWEEN '%s' AND '%s'",
    				mysql_real_escape_string($start),
    				mysql_real_escape_string($end));
    // I create my instance, with the SQL statement as parameter, and the connection if it's not the default one
    $table = new dataTable($sql,$connection2);
    // Now I make an array with the parameters for each column that I want to display
    // only title and name are mandatory
    // title will be the value displayed on the top row
    // name is the field name in the database
    // datafunc is the function used to display the data - otherwise it displays the raw data
    // dimension is the column dimension - you have to add the unit (% or px) - otherwise no width is specified
    $table->fields = array(
    			array ( 'name' => 'date',
    				  'title' => 'Date',
    				  'datafunc' => 'formatDate',
    				  'dimension' => '12%'
    				),
    			array ( 'name' => 'msisdn',
    				  'title' => 'Number',
    				  'datafunc' => '',
    				  'dimension' => '15%'
    				),
    			array ( 'name' => 'appID',
    				  'title' => 'Customer',
    				  'datafunc' => 'displayApp',
    				  'dimension' => '13%'
    				),
    			array ( 'name' => 'comment',
    				  'title' => 'Note',
    				  'datafunc' => '',
    				  'dimension' => '48%'
    				),
    			array ( 'name' => 'createdBy',
    				  'title' => 'Created By',
    				  'datafunc' => 'displayUser',
    				  'dimension' => '10%'
    				),
    		);
    // Now that our instance is created we can add other parameters (optional):
    $table->default_order = 'date';
    // Another parameter would be:
    $table->tr_function = 'createPopUp(\'test\',400,200,\'test.php\',\'$data[\\\'id\\\']\');';
    // Cet exemple de tr_function ne fonctionne pas et c'est la mon probleme...
    // tr_function allows you to have a javascript function triggered onclick on each row
    $table->processRequest();
    $pagination = $table->displayPagination();
    $restable = $table->displayTable();
     
     
    $results = <<<END
    <table cellpadding="4" cellspacing="0" width="100%" class="innerborder">
    	<tr>
    		<td class="head">
    		<table width="100%" cellpadding="0" cellspacing="0" border="0">
    			<tr>
    				<td width="50%" style="font-weight:bold">Notes History for the period between $start_date and $end_date</td>
    				<td width="50%" align="right">$pagination </td>
    			</tr>
    		</table>
    		</td>
    	</tr>
    	<tr>
    		<td class="white">
    		$restable
    		</td>
    	</tr>
    </table>
    END;
    Voila.
    Mon probleme vient de ma propriété
    $table->tr_function
    qui est un javascript que l'on peut rajouter sur la ligne. En l'occurence celui-ci devrait ouvrir une fausse popUp (un div) en ajax avec comme parametre l'ID de l'enregistrement.
    Je voudrais donc pouvoir accéder en dehors de ma classe a un des résultats de mon SELECT (le champ id), alors meme qu'il ne fait pas partie des résultats affichés.
    Je me dis qu'uns solution pourrait etre de l'appeler avec une forme particuliere (genre {--id--}), et de faire un regex dessus pour le remplacer par la valeur qu'il désigne, mais je ne trouve pas ca tres propre.
    Est-ce que qqun aurait une autre idée?

    Merci!

    PS: Désolé pour les commentaires en anglais, mais je travaille en Irlande. Si vous etes arrivé au bout ce ce POST et que vous avez une question, n'hésitez pas, je répondrai tres rapidement.

  2. #2
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 28
    Points : 25
    Points
    25
    Par défaut
    Bonjour,
    Je ne suis pas trop sûr d'avoir tout compris mais un tableau ne suffirait pas ? genre $table->donnees[$id][$donnee] ?

    Maxime.

  3. #3
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 211
    Points : 196
    Points
    196
    Par défaut
    Merci de ta réponse.
    Si, c'est ce a quoi je souhaite accéder, mais je ne peux pas y accéder en dehors de ma classe.
    Le tableau $data est défini dans ma classe, alors je me demande comment envoyer un parametre a ma classe qui serait une référence a ce tableau.

  4. #4
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 28
    Points : 25
    Points
    25
    Par défaut
    Une variable globale ?
    Genre $GLOBALS[$id][$donnee]

  5. #5
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 211
    Points : 196
    Points
    196
    Par défaut
    Non, je me demandais juste si il y avait une facon de faire particuliere propre aux classes dans ce genre de situation.
    Je crois que je vais faire un preg_replace.

  6. #6
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 022
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 022
    Points : 2 273
    Points
    2 273
    Par défaut
    Salut,
    tu peux te faire un getter :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    public getField($fieldName) {
    if(isset($this->data, $this->data[$fieldName])) {
    return $this->data[$fieldName];
    }
    return null;
    }
    Mais il faudra l'ajouter dans ton select : SELECT id, msisdn, etc.
    Après à toi de voir ce que tu veux retourner si le champ n'existe pas, tu peux aussi lancer une exception.
    D'autre part, vu que ta str tr_function est dans ta classe tu pourrais aussi le créer directement depuis la classe ou définir une fonction qui la crée.
    Vive les roues en pierre

Discussions similaires

  1. [POO] Accès à une instance objet depuis un enfant
    Par mokadjo dans le forum Général JavaScript
    Réponses: 16
    Dernier message: 09/07/2011, 00h30
  2. Accès au formulaire ouvert depuis une classe
    Par alband85 dans le forum C#
    Réponses: 32
    Dernier message: 27/06/2007, 16h38
  3. Réponses: 3
    Dernier message: 02/01/2007, 13h53
  4. Accès au fichier ressources depuis une classe action
    Par root76 dans le forum Struts 1
    Réponses: 2
    Dernier message: 21/11/2006, 07h36
  5. acces a uneressource bitmap depuis une classe
    Par firejocker dans le forum MFC
    Réponses: 9
    Dernier message: 03/02/2006, 21h48

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo