Précédent   Forum du club des développeurs et IT Pro > PHP > Langage > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, FAQ, sources, etc. pour PHP
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse
 
Outils de la discussion
Publicité
'
Vieux 25/07/2011, 16h58   #1
rawsrc
Modérateur
 
Avatar de rawsrc
 
Homme Martin
Dev indep
Inscription : mars 2004
Messages : 2 588
Détails du profil
Informations personnelles :
Nom : Homme Martin
Âge : 36
Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Dev indep

Informations forums :
Inscription : mars 2004
Messages : 2 588
Points : 6 046
Points : 6 046
Envoyer un message via Skype™ à rawsrc
Par défaut SplObjectStorage amélioré (3ème mot)

Bonjour à tous,

Ayant eu besoin d'utiliser massivement un SplObjectStorage, je me suis cogné à ses limitations par défaut. Du coup étant adepte du yaka se servir soi-même, j'ai décidé de l'améliorer en lui ajoutant des fonctionnalités qui m'ont été indispensables et surtout qui m'ont facilité grandement la vie.

Voici une classe SplObjectStoragePlus qui j'espère vous servira un jour :-)
Code :
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
<?php 
 
/**
 * Copyright (C) 2011+ Martin Lacroix
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * @license GNU General Public License Version 3 (GPLv3)
 * @link http://www.gnu.org/licenses/
 */
 
/**
 * PHP_VER   : PHP 5.3+ 
 * LIBRARIES : SPL
 * KEYWORDS  : SPLOBJECTSTORAGE EXTENDED IMPROVED
 *             SPLOBJECTSTORAGE ETENDU AMELIORE 
 * 
 * Class managing an extended SplObjectStorage
 * New features: 
 *    - always move the internal pointer to the last object inserted into the storage   
 *    - compute the hashcode of any arbitrary object without inserting it into the storage
 *    - read the hashcode of every or all objects in the storage
 *    - access an object by its hashcode or position in the storage
 *    - directly access the data attached to an object by its hashcode or position in the storage
 * 
 * Classe gérant un SplObjectStorage amélioré
 * Nouveautés :
 *    - déplace automatiquement le pointeur interne sur le dernier objet inséré
 *    - calcule le hashcode de n'importe quel objet sans l'insérer dans le silo
 *    - extraction d'un ou de tous les hashcodes du silo
 *    - sélection d'un objet identifié par son hashcode ou sa position dans le silo
 *    - lecture directe des infos attachées à un objet identifié par son hashcode ou sa position dans le silo
 * 
 * @package tools
 * @version 1.0.0
 * @author Martin Lacroix
 */
class SplObjectStoragePlus extends SplObjectStorage {
 
   private $_map   = array();
   private $_index = -1;
 
   /**
    * @param SplObjectStorage $storage
    */
   function addAll(SplObjectStorage $storage) {
      $storage->rewind();
      while($storage->valid()) {
         $this->offsetSet($storage->current(), $storage->getInfo());
         $storage->next();
      }
   }
 
   /**
    * Add an object to the storage
    * @param object $object
    * @param mixed $data
    */
   function attach($object, $data = NULL) {
      $this->offsetSet($object, $data);
   }
 
   /**
    * Remove an object from the storage
    * @param object object
    */
   function detach($object) {
      $this->offsetUnset($object);
   }
 
   /**
    * Add an object to the storage and set the internal pointer on it
    * @param object $object
    * @param mixed $data
    */
   function offsetSet($object, $data = NULL) {
      $hash = spl_object_hash($object);
      if (FALSE === array_search($hash, $this->_map, TRUE)) {
         parent::attach($object, $data);
         $this->_map[++$this->_index] = $hash;
         $this->selectObjectByKey($this->_index);
      }
   }
 
   /**
    * Remove an object from the storage
    * @param object object
    */
   function offsetUnset($object) {
      $index = array_search(spl_object_hash($object), $this->_map, TRUE);
      if (FALSE !== $index) {
         parent::offsetUnset($object);
         unset($this->_map[$index]);
      }
   }
 
   /**
    * @param SplObjectStorage $storage
    */
   function removeAll(SplObjectStorage $storage) {
      $storage->rewind();
      while($storage->valid()) {
         $this->offsetUnset($storage->current());
         $storage->next();
      }
   }
 
   /**
    * @param SplObjectStorage $storage
    */
   function removeAllExcept(SplObjectStorage $storage) {
      parent::rewind();
      while(parent::valid()) {
         $current = parent::current();
         parent::next();
         if ( ! $storage->contains($current)) {
            $this->offsetUnset($object);
         }
      }
   }
 
   /**
    * Returns the hashcode of the current object
    * @return string
    */
   function getHash() {
      return spl_object_hash(parent::current());
   }
 
   /**
    * Returns the object identified by its hashcode
    * @param string $hash
    * @return object|NULL
    */
   function getObjectByHash($hash) {
      $index = array_search($hash, $this->_map);
      if (FALSE !== $index) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $index) {
               return parent::current();
            }
            parent::next();
         }
      }
   }
 
   /**
    * Returns the position of an object in the storage
    * Object identified by its hashcode
    * @param string $hash
    * @return int|NULL
    */
   function getKeyByHash($hash) {
      $index = array_search($hash, $this->_map, TRUE);
      return (FALSE === $index) ? NULL : $index;
   }
 
   /**
    * Returns the hashcode of an object identified by its position
    * @param int $key
    * @return string|NULL
    */
   function getHashByKey($key) {
      return $this->_map[$key];
   }
 
   /**
    * Returns the data associated with an object identified by its hashcode
    * @param string $hash
    * @return mixed|NULL
    */
   function getInfoByHash($hash) {
      $index = array_search($hash, $this->_map, TRUE);
      if (FALSE !== $index) {
         return $this->getInfoByKey($index);
      }
   }
 
   /**
    * Returns the data associated with an object identified by its position
    * @param int $key
    * @return mixed|NULL
    */
   function getInfoByKey($key) {
      if (isset($this->_map[$key])) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $key) {
               return parent::getInfo();
            }
            parent::next();
         }
      }
   }
 
   /**
    * Move the internal pointer to an object identified by its hashcode
    * @param mixed $hash
    * @return bool FALSE if the object doesn't exist
    */
   function selectObjectByHash($hash) {
      $index = array_search($hash, $this->_map, TRUE);
      return (FALSE !== $index) 
                ? $this->selectObjectByKey($index)
                : FALSE;
   }
 
   /**
    * Move the internal pointer to an object identified by its position in the storage
    * @param int $key
    * @return bool FALSE if the object doesn't exist
    */
   function selectObjectByKey($key) {
      if (isset($this->_map[$key])) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $key) {
               return TRUE;
            }
            parent::next();
         }
      }
      return FALSE;
   }
 
   /**
    * Returns the hashcode of the object in parameter
    * @param mixed $object
    * @return string
    */
   static function computeHash($object) {
      return spl_object_hash($object);
   }
 
   /**
    * Returns the array of hashs
    * @return array Array(position in the storage => hashcode)
    */
   function allHashs() {
      return $this->_map;
   }
}
?>
Si vous tombez sur un problème n'hésitez pas à m'en faire part.
Bon code
__________________
# Dans la Création, tout est permis mais tout n'est pas utile...
rawsrc est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 25/07/2011, 17h45   #2
stealth35
Modérateur
 
Inscription : septembre 2010
Messages : 7 958
Détails du profil
Informations forums :
Inscription : septembre 2010
Messages : 7 958
Points : 9 508
Points : 9 508
Citation:
A cause de certaines limitations de PHP (ou fonctionnalités...), il est impossible de parcourir la classe en utilisant foreach() ou each().
t'as un exemple ?
__________________
http://blog.stealth35.com/
stealth35 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 25/07/2011, 18h29   #3
rawsrc
Modérateur
 
Avatar de rawsrc
 
Homme Martin
Dev indep
Inscription : mars 2004
Messages : 2 588
Détails du profil
Informations personnelles :
Nom : Homme Martin
Âge : 36
Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Dev indep

Informations forums :
Inscription : mars 2004
Messages : 2 588
Points : 6 046
Points : 6 046
Envoyer un message via Skype™ à rawsrc
Salut stealth35,

Laisse tomber, j'ai fait du copier coller comme un âne d'un précédent post.
Je corrige de suite.

Désolé
__________________
# Dans la Création, tout est permis mais tout n'est pas utile...
rawsrc est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/01/2012, 10h47   #4
Benjamin Delespierre
Modérateur
 
Avatar de Benjamin Delespierre
 
Benjamin Delespierre
Développeur Web
Inscription : février 2010
Messages : 3 890
Détails du profil
Informations personnelles :
Nom : Benjamin Delespierre
Âge : 25
Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Opérateur de télécommunications

Informations forums :
Inscription : février 2010
Messages : 3 890
Points : 8 582
Points : 8 582
Y'a une chose que je comprends pas bien dans ta classe. Elle se comporte plus ou moins comme un tableau associatif (la récupération par hash en plus c'est vrai).

Concrètement, qu'est ce qu'elle apporte de plus par rapport à ArrayIterator ou ArrayObject ?
__________________
On vous a menti
PHP, Injection de dépendances et composants
La POO en PHP en 10 minutes pour moins
Suivez-moi sur GitHub et Twitter

N'oubliez pas de vous servir des bouttons , et
Benjamin Delespierre est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/01/2012, 11h27   #5
rawsrc
Modérateur
 
Avatar de rawsrc
 
Homme Martin
Dev indep
Inscription : mars 2004
Messages : 2 588
Détails du profil
Informations personnelles :
Nom : Homme Martin
Âge : 36
Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Dev indep

Informations forums :
Inscription : mars 2004
Messages : 2 588
Points : 6 046
Points : 6 046
Envoyer un message via Skype™ à rawsrc
Bonjour,

Oui je m'étais posé la question mais j'avais absolument besoin d'un SplObjectStorage (extension d'un framework en clientèle). Par ailleurs il faut savoir ceci :
Citation:
PHP arrays are in fact implemented as ordered hashtables
Et qui dit hashtable dit SplObjectStorage pour de très bonnes performances. D'ailleurs j'ai amélioré les perfs de cette classe après avoir mené des tests surtout au niveau des searchs : array_search() (même avec comparaison typée) est bien plus lent que SplObjectStorage::contains()
Voici la version 1.0.1 (LGPLv3):
Code :
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<?php
 
/**
 * Copyright (C) 2011+ Martin Lacroix
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * @license GNU Lesser General Public License Version 3 (LGPLv3)
 * @link http://www.gnu.org/licenses/
 */
 
/**
 * PHP_VER   : PHP 5.3+
 * LIBRARIES : SPL
 * KEYWORDS  : SPLOBJECTSTORAGE EXTENDED IMPROVED
 *             SPLOBJECTSTORAGE ETENDU AMELIORE
 *
 * Class managing an extended SplObjectStorage
 * New features:
 *    - always move the internal pointer to the last added object
 *    - compute the hashcode of any arbitrary object without adding it into the storage
 *    - read the hashcode of every or all objects in the storage
 *    - access an object by its hashcode or position in the storage
 *    - directly access the data attached to an object by its hashcode or position in the storage
 *
 * Classe gérant un SplObjectStorage amélioré
 * Nouveautés :
 *    - déplace automatiquement le pointeur interne sur le dernier objet inséré
 *    - calcule le hashcode de n'importe quel objet sans l'insérer dans le silo
 *    - extraction d'un ou de tous les hashcodes du silo
 *    - sélection d'un objet identifié par son hashcode ou sa position dans le silo
 *    - lecture directe des infos attachées à un objet identifié par son hashcode ou sa position dans le silo
 *
 * @package tools
 * @version 1.0.1
 * @author Martin Lacroix
 */
class SplObjectStoragePlus
   extends \SplObjectStorage
{
   /**
    * @var array Array(index => hashcode)
    */
   private $map   = array();
   private $index = -1;
 
   /**
    * @param SplObjectStorage $storage
    */
   public function addAll(\SplObjectStorage $storage) {
      $storage->rewind();
      while($storage->valid()) {
         $this->offsetSet($storage->current(), $storage->getInfo());
         $storage->next();
      }
   }
 
   /**
    * Add an object to the storage
    * @param object $object
    * @param mixed $data
    */
   public function attach($object, $data = null) {
      $this->offsetSet($object, $data);
   }
 
   /**
    * Remove an object from the storage
    * @param object object
    */
   public function detach($object) {
      $this->offsetUnset($object);
   }
 
   /**
    * Add an object to the storage and set the internal pointer on it
    * @param object $object
    * @param mixed $data
    */
   public function offsetSet($object, $data = null) {
      if ( ! parent::contains($object)) {
         parent::attach($object, $data);
         $this->map[++$this->index] = spl_object_hash($object);
         while(parent::valid()) {
            parent::next();
         }
      }
   }
 
   /**
    * Remove an object from the storage
    * @param object object
    */
   public function offsetUnset($object) {
      if (parent::contains($object)) {
         parent::offsetUnset($object);
         $index = array_search(spl_object_hash($object), $this->map, true);
         unset($this->map[$index]);
      }
   }
 
   /**
    * @param SplObjectStorage $storage
    */
   public function removeAll(\SplObjectStorage $storage) {
      $storage->rewind();
      while($storage->valid()) {
         $this->offsetUnset($storage->current());
         $storage->next();
      }
   }
 
   /**
    * @param SplObjectStorage $storage
    */
   public function removeAllExcept(\SplObjectStorage $storage) {
      parent::rewind();
      while(parent::valid()) {
         $current = parent::current();
         parent::next();
         if ( ! $storage->contains($current)) {
            $this->offsetUnset($object);
         }
      }
   }
 
   /**
    * Returns the hashcode of the current object
    * @return string
    */
   public function getHash() {
      return spl_object_hash(parent::current());
   }
 
   /**
    * Returns the object identified by its hashcode
    * @param string $hash
    * @return object|null
    */
   public function getObjectByHash($hash) {
      $index = array_search($hash, $this->map, true);
      if (false !== $index) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $index) {
               return parent::current();
            }
            parent::next();
         }
      }
   }
 
   /**
    * Returns the object identified by its position in the storage
    * @param int $key
    * @return object|null
    */
   public function getObjectByKey($key) {
      if (isset($this->map[$key])) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $key) {
               return parent::current();
            }
            parent::next();
         }
      }
   }
 
   /**
    * Returns the object identified by its attached info
    * In case of many identical infos, the first attached object is returned
    * @param mixed $info
    * @return object|null
    */
   public function getObjectByInfo($info) {
      parent::rewind();
      while(parent::valid()) {
         if (parent::getInfo() === $info) {
            return parent::current();
         }
         parent::next();
      }
   }
 
   /**
    * Returns the position of an object in the storage
    * Object identified by its hashcode
    * @param string $hash
    * @return int|null
    */
   public function getKeyByHash($hash) {
      $index = array_search($hash, $this->map, true);
      return (false === $index) ? null : $index;
   }
 
   /**
    * Returns the hashcode of an object identified by its position
    * @param int $key
    * @return string|null
    */
   public function getHashByKey($key) {
      return $this->map[$key];
   }
 
   /**
    * Returns the data associated with an object identified by its hashcode
    * @param string $hash
    * @return mixed|null
    */
   public function getInfoByHash($hash) {
      $index = array_search($hash, $this->map, true);
      if (false !== $index) {
         return $this->getInfoByKey($index);
      }
   }
 
   /**
    * Returns the data associated with an object identified by its position
    * @param int $key
    * @return mixed|null
    */
   public function getInfoByKey($key) {
      if (isset($this->map[$key])) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $key) {
               return parent::getInfo();
            }
            parent::next();
         }
      }
   }
 
   /**
    * Move the internal pointer to an object identified by its hashcode
    * @param mixed $hash
    * @return bool false if the object doesn't exist
    */
   public function selectObjectByHash($hash) {
      $index = array_search($hash, $this->map, true);
      return (false !== $index)
                ? $this->selectObjectByKey($index)
                : false;
   }
 
   /**
    * Move the internal pointer to an object identified by its position in the storage
    * @param int $key
    * @return bool false if the object doesn't exist
    */
   public function selectObjectByKey($key) {
      if (isset($this->map[$key])) {
         parent::rewind();
         while(parent::valid()) {
            if (parent::key() === $key) {
               return true;
            }
            parent::next();
         }
      }
      return false;
   }
 
   /**
    * Select the object identified by its attached info
    * In case of many identical infos, the first attached object is selected
    * @param mixed $info
    * @return bool false if the object doesn't exist
    */
   public function selectObjectByInfo($info) {
      parent::rewind();
      while(parent::valid()) {
         if (parent::getInfo() === $info) {
            return true;
         }
         parent::next();
      }
      return false;
   }
 
   /**
    * Returns the hashcode of the object in parameter
    * @param mixed $object
    * @return string
    */
   static public function computeHash($object) {
      return spl_object_hash($object);
   }
 
   /**
    * Returns the array of hashs
    * @return array array(position in the storage => hashcode)
    */
   public function allHashs() {
      return $this->map;
   }
}
?>
__________________
# Dans la Création, tout est permis mais tout n'est pas utile...
rawsrc est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/01/2012, 12h03   #6
Benjamin Delespierre
Modérateur
 
Avatar de Benjamin Delespierre
 
Benjamin Delespierre
Développeur Web
Inscription : février 2010
Messages : 3 890
Détails du profil
Informations personnelles :
Nom : Benjamin Delespierre
Âge : 25
Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Opérateur de télécommunications

Informations forums :
Inscription : février 2010
Messages : 3 890
Points : 8 582
Points : 8 582
Vu que j'ai un peu la paresse de le faire mais que tu l'as sûrement fait, tu as les résultats du benchmark ? S'il est vrai que ton mécanisme est plus performant, je serais bien tenté de m'en servir pour Axiom (j'ai quelques idées d'implem où ça pourrait servir).
__________________
On vous a menti
PHP, Injection de dépendances et composants
La POO en PHP en 10 minutes pour moins
Suivez-moi sur GitHub et Twitter

N'oubliez pas de vous servir des bouttons , et
Benjamin Delespierre est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/01/2012, 14h07   #7
rawsrc
Modérateur
 
Avatar de rawsrc
 
Homme Martin
Dev indep
Inscription : mars 2004
Messages : 2 588
Détails du profil
Informations personnelles :
Nom : Homme Martin
Âge : 36
Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

Informations professionnelles :
Activité : Dev indep

Informations forums :
Inscription : mars 2004
Messages : 2 588
Points : 6 046
Points : 6 046
Envoyer un message via Skype™ à rawsrc
Lors des benchs j'avais testé la vitesse de remplissage et la vitesse de recherche.
Array avec array_search() et SplObjectStorage avec contains().
Voici ce que cela m'avait sorti :
Code :
1
2
3
4
5
arrFill : 0.2472128868103
arrRead : 0.0036439895629883
 
splFill : 0.54245090484619
splRead : 9.0599060058594E-6
Désolé mais pas moyen de retrouver le code du bench. J'avais collé les résultats avec mon code pour mémo et c'est tout. Je vais fouiller.
__________________
# Dans la Création, tout est permis mais tout n'est pas utile...
rawsrc est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse
Outils de la discussion

Navigation rapide


Fuseau horaire GMT +2. Il est actuellement 17h06.


 
 
 
 
Partenaires

Hébergement Web