Nested data via DOM

Gepost door Arian Stolwijk op 27-01-2009 17:21.

Een oneindige diepte maken voor bijvoorbeeld een menu, mappenstructuur. Nu met DOM.

Het voordeel met werken met DOM is dat je op een relatief gemakkelijke manier de parent node en en de child nodes kunt bereiken.

In principe maakt het van 2 dimensionale data (bijvoorbeeld uit een database) een geneste DOMDocument.

Aangezien DOMDocument af en toe toch nog best lastig is, heb ik er het e.e.a. omheengebouwd zodat alles simpel te benaderen is.

Zoals je ziet heten mijn classes:
- Nested
- Nested_Child
- Nested_Children
- Nested_Child_Properties
- Nested_Exception

Deze komen dus overeen met de bestanden:
- Nested.php
- Nested/Child.php
- Nested/Children.php
- Nested/Child/Properties.php
- Nested/Exception.php

Het voorbeeld staat helemaal onderaan.
Het komt er op neer dat je eerst de data in de class gooit met de Nested->addChild() method.
De eerste parameter is het ID, de 2e is het id van het parent element. De derde parameter is de bijbehorende data bij het element (de 'properties').

Vervolgens kan je direct al met Nested->getElements() de elementen loopen, omdat getElements() een iteratable object terug geeft (Nested_Children) waar de elementen (Nested_Child) inzitten.

Het Nested_Child element heeft een aantal methods, bijvoorbeeld:
- getParent() - deze geeft het Nested_Child object terug van het parent element
- getChildren() - deze geeft een Nested_Children object terug met een verzameling van Nested_Child objects
- getProperties() - deze geeft het Nested_Child_Properties object terug. Deze kan je met de __get() magic method benaderen om de data snel op te vragen. Dit object kan je tevens loopen met bijvoorbeeld foreach en while.

De Nested class zelf heeft naast addChild() en getElements() ook nog een method getElement()
Met deze method ga je zoeken naar een bepaald element. Deze geeft dan ook een Nested_Child object terug.

De Nested class heeft ook nog een debug() method, deze zet wat xml op het scherm, zodat je snel de structuur van je elementen boom kunt zien.

Bestanden van dit script

index.php

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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<?php

// Nested.php

include 'Nested/Exception.php';
include 'Nested/Child.php';
include 'Nested/Child/Properties.php';

class Nested {

    /**
     *
     * @var DOMDocument
     */
    protected $doc;

    /**
     * Properties collection
     * @var array
     */
    static public $propertiesCollection = array();

    /**
     * If an element is added, when the parent element isn't already added, the element
     * will stored temporary in this array
     *
     * @var array
     */
    protected $noParentCollection = array();

    /**
     * Create the DOMDocument object
     */
    public function __construct(){
        $this->doc = new DOMDocument();
    }

    /**
     *
     * @param $id
     * @param $parent_id
     * @param $properties
     * @return unknown_type
     */
    public function addChild($id,$parent_id=0,$properties=array()){
        if(!(ctype_digit($id) || is_int($id)) || $id <= 0 || isset(self::$propertiesCollection[$id])){
            throw new Nested_Exception('The ID must be a unique positive integer');
        }

        // Properties
        self::$propertiesCollection[$id] = new Nested_Child_Properties($properties);

        // Create the element
        $newElmt = $this->doc->createElement('child');

        // Add ID attribute
        $idAttr = $this->doc->createAttribute('id');
        $idAttr->appendChild($this->doc->createTextNode('id'.$id));
        $newElmt->appendChild($idAttr);
        $newElmt->setIdAttribute('id',true);

        // Check if the element has a parent
        if($parent_id > 0){
            $parentElmt = (int)$parent_id > 0 ? $this->doc->getElementById('id'.$parent_id) : null;
            if($parentElmt instanceof DOMElement){
                // If there's a parent element found, append this new element to the parent element
                $parentElmt->appendChild($newElmt);
            }else{
                // The parent is not found, store the element and wait till the parent element
                // gets added
                $this->noParentCollection[$parent_id] = $newElmt;
            }
        }else{
            $this->doc->appendChild($newElmt);
        }

        // There is a child element of this element who is already added
        if(isset($this->noParentCollection[$id])){
            $newElmt->appendChild($this->noParentCollection[$id]);
            unset($this->noParentCollection[$id]);
        }
    }

    /**
     *
     * @param int $id
     * @return Nested_Child
     */
    public function getElement($id){
        $elmt = $this->doc->getElementById('id'.$id);
        if($elmt instanceof DOMElement){
            return new Nested_Child($elmt);
        }
        throw new Nested_Exception('This element does not exists');
    }

    /**
     * Get the elements at the 'root' level
     * @return Nested_Children
     */
    public function getElements(){
        $childElmts = $this->doc->childNodes;
        $children = new Nested_Children();
        foreach($childElmts as $elmt){
            print_r($elmt);
            $children->addChild(new Nested_Child($elmt));
        }
        return $children;
    }

    /**
     * Shows the hierarchy in XML
     * @param int $id If you want to view the hierarchy of an element
     * @return void
     */
    public function debug($id=null){
        $this->doc->formatOutput = true;

        $node = null;
        if(!empty($id)){
            $node = $this->getElement($id)->getDOMElement();
        }
        echo '<pre>'.htmlentities($this->doc->saveXML($node),true).'</pre>';
    }

    /**
     * Clear the memory
     * @return void
     */
    public function __destruct(){
        unset($this->doc);
    }

}


// Nested/Child.php

include 'Children.php';

class Nested_Child {

    /**
     *
     * @var DOMElement
     */
    protected $elmt;

    /**
     *
     * @var int
     */
    protected $id;

    /**
     *
     * @param DOMElement $elmt
     */
    public function __construct(DOMElement $elmt){
        $this->elmt = $elmt;
    }

    /**
     * Get the element ID
     * @return int
     */
    public function getId(){
        if(empty($this->id)){
            $this->id = (int) substr($this->elmt->getAttribute('id'),2);
        }
        return $this->id;
    }

    /**
     * Get the parent element
     * @return Nested_Child
     */
    public function getParent(){
        $parent = $this->elmt->parentNode;
        if($parent instanceof DOMElement){
            return new Nested_Child($parent);
        }
        throw new Nested_Exception('This parent element does not exists');
    }

    /**
     * Get the element properties
     * @return Nested_Child_Properties
     */
    public function getProperties(){
        $properties = isset(Nested::$propertiesCollection[$this->getId()]) ?
            Nested::$propertiesCollection[$this->getId()] :
            new Nested_Child_Properties(array());
        return $properties;
    }

    /**
     * Check if the element has child nodes
     * @return bool
     */
    public function hasChildren(){
        return $this->elmt->hasChildNodes();
    }

    /**
     * Get the element children
     * @return Nested_Children
     */
    public function getChildren(){
        $childElmts = $this->elmt->childNodes;
        $children = new Nested_Children();
        foreach($childElmts as $elmt){
            $children->addChild(new Nested_Child($elmt));
        }
        return $children;
    }

    /**
     *
     * @return DOMElement
     */
    public function getDOMElement(){
        return $this->elmt;
    }

}

// Nested/Children.php


class Nested_Children implements Iterator, Countable {

    /**
     * The children
     *
     * @var array
     */
    protected $children = array();

    /**
     * Add a child
     *
     * @param Nested_Child $child
     */
    public function addChild(Nested_Child $child){
        $this->children[$child->getId()] = $child;
    }

    /**
     * Get a child
     *
     * @param string $key The ID of the child
     * @return Nested_Child
     */
    public function __get($key){
        if(isset($this->children[$key])){
            return $this->children[$key];
        }
        return false;
    }

    /**
     * If the Child is already added to the children
     *
     * @param string $key The ID of the child
     * @return bool true if the child isset, otherwise false
     */
    public function __isset($key){
        return isset($this->children[$key]);
    }

    /**
     * Count the children
     *
     * @return int
     */
    public function count(){
        return count($this->children);
    }


    /**
     *
     * @return bool
     */
    public function rewind() {
        reset($this->children);
    }

    /**
     *
     * @return Nested_Child
     */
    public function current() {
        return current($this->children);
    }

    /**
    * @var string|int
     */
    public function key() {
        return key($this->children);
    }

    /**
     *
     * @return Nested_Child|false
     */
    public function next() {
        return next($this->children);
    }

    /**
     *
     * @return bool
     */
    public function valid() {
        return $this->current() !== false;
    }
}


// Nested/Child/Properties.php


class Nested_Child_Properties implements Iterator, Countable {

    /**
     * The properties of a element
     *
     * @var array
     */
    protected $properties = array();

    /**
     * Create a properties instance
     *
     * @param array $properties
     */
    public function __construct(array $properties){
        $this->properties = $properties;
    }

    /**
     * Return a property
     *
     * @param string $key Property Key
     * @return mixed The property value, if the property does not exists, it returns false
     */
    public function __get($key){
        if(isset($this->properties[$key])){
            return $this->properties[$key];
        }
        return false;
    }

    /**
     * Set a property
     *
     * @param string $key
     * @param mixed $value
     */
    public function __set($key,$value){
        $this->properties[$key] = $value;
    }

    /**
     * Checks if the property isset
     *
     * @param string $key
     * @return bool True if the property isset, otherwise false
     */
    public function __isset($key){
        return isset($this->properties[(string)$key]);
    }

    public function count(){
        return count($this->properties);
    }

    /**
     * Make the properties iteratable
     */

    public function rewind() {
        reset($this->properties);
    }

    public function current() {
        return current($this->properties);
    }

    public function key() {
        return key($this->properties);
    }

    public function next() {
        return next($this->properties);
    }

    public function valid() {
        return $this->properties() !== false;
    }

}

// Nested/Exception.php

class Nested_Exception extends Exception {
        
}


// Voorbeeld

$i = 1;

$nested = new Nested();

// Elementen toevoegen
$nested->addChild($i,0,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));
$nested->addChild($i,0,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

// Zoals je ziet, heeft dit element de parent met id=5. Deze is helaas nog 
//niet toegevoegd. Daarom zal dit element even tijdelijk worden opgeslagen 
//en wordt alsnog toegevoegd als child van id=5 als het element met id=5 
//toegevoegd wordt.
$nested->addChild($i,5,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

$nested->addChild($i,1,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

// Nu wordt dus het element met ID=3 toegevoegd aan dit element
$nested->addChild($i,2,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));
$nested->addChild($i,2,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

$children = $nested->getElement(1)->getChildren();
foreach($children as $child){
    echo $child->getProperties()->tekst.'<br />';
}

echo $nested->getElement(4)->getParent()->getProperties()->naam;

$nested->debug();

?>

Commentaar

28-01-2009 09:39

Ziet er netjes uit.
Maar wat is het voordeel van deze boven?

http://nl2.php.net/xmlwriter

1
N.V.T.
28-01-2009 16:00

Vermeld hier alle zaken betreffende valkuilen, handige informatie, (installatie-)instructies e.d.

1
2
3
Zo ver ik weet maakt XMLWriter xml, en is dat ook het doel van XMLWriter.

Het doel van mijn classes is juist om bijvoorbeeld nested menu's te maken, mappenstructuren, sitemap-trees, etc.
Inloggen wachtwoord vergeten? Aanmelden