extending Zend_Db_Table to create NestedSet models

Last days I’ve been trying to customize Zend’s Framework. My goal is to create simpler models. Currently I’m making some db models that handle stuff around wide used designs. Such design is the Nested Set model. It is an adjacent list realized in SQL as a tree. You can find a good introduction to nested sets at mysql developer zone.

Now let’s create a basic table.

1
2
3
4
5
6
CREATE TABLE nested_table (
    `nested_table_id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `nested_table_left` int UNSIGNED NOT NULL,
    `nested_table_right` int UNSIGNED NOT NULL,
    `nested_table_name` varchar(60) NOT NULL
);

And now let’s create a model that will work with this table.

1
2
3
4
5
6
7
8
class NestedTable extends Custom_Db_Nestedset {
    //basic mapping
    protected $_name     = "nested_table"; //table name
    protected $_primary  = "nested_table_id"; //primary key
    protected $_left     = "nested_table_left"; //left column
    protected $_right    = "nested_table_right"; //right column
    protected $_toString = "nested_table_name"; //used when retrieving tree. if not set primary key will be used
}

And that’s it. Now we have class that work as a nested set. Here is example controller.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class NestedController extends Zend_Controller_Action {
 
    public function testAction()
    {
        $table = new NestedTable;
        $root  = $table->createRoot(); //creating root node.
        $node1 = $table->insertAsFirstChildOf($root); //insert as first child of root category.
        $node2 = $table->insertAsNextSiblingOf($node1); //insert node next to given node. In our case next to node1.
        $node3 = $table->insertAsPrevSiblingOf($node2); //insert node before given node.
        $node4 = $table->insertAsLastChildOf($root); //insert node as last child of root category.
 
        $node2_1 = $table->insertAsFirstChildOf($node2); //go one level deeper.
        $table->deleteNode($node2);// delete node2 and his childs.
 
        $table->getTree(); //retrieve full tree (subtrees are still not supported)
    }
}

and here is the nested set class.

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
<?php
 
/**
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license
 *
 * @category  Custom
 * @package  Custom_Db
 * @subpackage Nestedset
 * @copyright Copyright (c) 2008 Ivan Iordanov <ivan@iordanov.net>
 * @version  $Id: Nestedset.php 2008-06-06
 * @see    http://dev.mysql.com/tech-resources/articles/hierarchical-data.html
 */
 
 
/**
 * @see Zend_Db_Table
 */
require_once 'Zend/Db/Table.php';
 
/**
 * Class for SQL Nested set interface.
 *
 * @category  Custom
 * @package  Custom_Db
 * @subpackage Nestedset
 * @copyright Copyright (c) 2008 Ivan Iordanov (http://dev.iordanov.net)
 */
 
class Custom_Db_Nestedset extends Zend_Db_Table
{
 
    /**
    * left column in nested table
    *
    * @var String
    */
    protected $_left;
 
    /**
    * right column in nested table
    *
    * @var String
    */
    protected $_right;
 
    /**
    * Column to be retrieved with getTree method
    * If not set primary key will be used.
    *
    * @var String
    */
    protected $_toString;
 
    /**
    * Additional data to be inserted.
    *
    * @var Array
    */
    private  $_insertData = array();
 
    /**
    * constructor
    */
    public function __construct()
    {
        parent::__construct();
        if (!$this->_toString)
        {
            $this->_toString = $this->_primary[1];
        }
    }
 
    /**
    * Additional data to be inserted
    *
    * @param array
    * @access public
    */
    public function setInsertData(array $data)
    {
        $this->_insertData = $data;
    }
 
    /**
    * Retrieve whole tree
    *
    * @access public
    * @return array
    */
    public function getTree()
    {
        //todo: add custom node
        $ret = $this->_db->query("
            SELECT COUNT(parent.{$this->_primary[1]}) - 1 as depth, node.{$this->_toString}
            FROM {$this->_name} AS node, {$this->_name} AS parent
            WHERE node.{$this->_left}
            BETWEEN parent.{$this->_left}
            AND parent.{$this->_right}
            GROUP BY node.{$this->_primary[1]}
            ORDER BY node.{$this->_left}
        ");
        return $ret->fetchAll();
 
    }
 
    /**
    * Insert node as first child
    *
    * @param int
    * @access public
    * @return int
    */
    public function insertAsFirstChildOf($id)
    {
        $row = $this->retrieveData($id);
 
        $right = (int) $row->{$this->_right};
        $left  = (int) $row->{$this->_left};
 
        $this->_db->query("UPDATE {$this->_name} SET {$this->_right} = {$this->_right} + 2 WHERE {$this->_right} > {$left}");
        $this->_db->query("UPDATE {$this->_name} SET {$this->_left} = {$this->_left} + 2 WHERE {$this->_left} > {$left}");
 
        $data = array(
            $this->_left => $left + 1,
            $this->_right => $left + 2
        );
        $this->_insertData = array_merge($this->_insertData, $data);
 
        return $this->insert($this->_insertData);
    }
 
    /**
    * Insert node as last child
    *
    * @param int
    * @access public
    * @return int
    */
    public function insertAsLastChildOf($id)
    {
        $row = $this->retrieveData($id);
 
        $right = (int) $row->{$this->_right};
        $left  = (int) $row->{$this->_left};
 
        $this->_db->query("UPDATE {$this->_name} SET {$this->_right} = {$this->_right} + 2 WHERE {$this->_right} >= {$right}");
        $this->_db->query("UPDATE {$this->_name} SET {$this->_left} = {$this->_left} + 2 WHERE {$this->_left} > {$right}");
 
 
        $data = array(
            $this->_left => $right,
            $this->_right => $right + 1,
        );
        $this->_insertData = array_merge($this->_insertData, $data);
 
        return $this->insert($this->_insertData);
 
    }
 
    /**
    * Insert node as next sibling of given node
    *
    * @param int
    * @access public
    * @return int
    * @throws Exception
    */
    public function insertAsNextSiblingOf($id)
    {
        $row = $this->retrieveData($id);
        $right = (int) $row->{$this->_right};
        $left  = (int) $row->{$this->_left};
 
        if ($left === 1) {
            throw new Exception("Root node can't have siblings");
        }
 
        $this->_db->query("UPDATE {$this->_name} SET {$this->_right} = {$this->_right} + 2 WHERE {$this->_right} > {$right}");
        $this->_db->query("UPDATE {$this->_name} SET {$this->_left} = {$this->_left} + 2 WHERE {$this->_left} > {$right}");
 
 
        $data = array(
            $this->_left => $right+1,
            $this->_right => $right + 2,
        );
 
        $this->_insertData = array_merge($this->_insertData, $data);
        return $this->insert($this->_insertData);
 
    }
 
    /**
    * Insert node as prev sibling of given node
    *
    * @param int
    * @access public
    * @return int
    * @throws Exception
    */
    public function insertAsPrevSiblingOf($id)
    {
        $row = $this->retrieveData($id);
        $right = (int) $row->{$this->_right};
        $left  = (int) $row->{$this->_left};
 
        if ($left === 1) {
            throw new Exception("Root node can't have siblings");
        }
 
 
        $this->_db->query("UPDATE {$this->_name} SET {$this->_right} = {$this->_right} + 2 WHERE {$this->_right} > {$left}");
        $this->_db->query("UPDATE {$this->_name} SET {$this->_left} = {$this->_left} + 2 WHERE {$this->_left} >= {$left}");
 
 
        $data = array(
            $this->_left => $left,
            $this->_right => $left + 1,
        );
 
        $this->_insertData = array_merge($this->_insertData, $data);
        return $this->insert($this->_insertData);
    }
 
    /**
    * Delete node with it's child(s) and return affected rows
    *
    * @param int
    * @access public
    * @return int
    */
 
    public function deleteNode($id)
    {
        $row = $this->retrieveData($id);
        $right = (int) $row->{$this->_right};
        $left  = (int) $row->{$this->_left};
        $width = $right - $left + 1;
        $res = $this->_db->query("DELETE FROM {$this->_name} WHERE {$this->_left} BETWEEN {$left} AND {$right}");
 
        $this->_db->query("UPDATE {$this->_name} SET {$this->_right} = {$this->_right} - {$width} WHERE {$this->_right} > {$right}");
        $this->_db->query("UPDATE {$this->_name} SET {$this->_left} = {$this->_left} - {$width} WHERE {$this->_left} > {$right}");
 
        return $res->rowCount();
    }
 
    /**
    * Insert root node
    *
    * @access public
    * @return int
    */
    public function createRoot()
    {
 
        $data = array(
            $this->_left => 1,
            $this->_right => 2
        );
        $this->_insertData = array_merge($this->_insertData, $data);
        return $this->insert($this->_insertData);
    }
 
    /**
    * Insert node
    *
    * @param int
    * @access private
    * @return Zend_Db_Row
    */
    private function retrieveData($id)
    {
        $select = $this->select()->where($this->_primary[1] .' = ?', $id);
        return $this->fetchRow($select);
    }
}

Share/Save/Bookmark

7 Responses to “extending Zend_Db_Table to create NestedSet models”

  1. Cory Says:

    Awesome work, this will really actually help me a lot. I have a bunch of tables with adjacency going on and a very kludgey way of handling inserts and updates on those tables, so this class will help a lot. Keep up the great work!

  2. Alex Says:

    Wow thats good. Thanks.
    I will youse it in next time.

  3. Ren? Leonhardt Says:

    Good to see the first support for NestedSets in ZF.
    I am missing some move methods:
    moveNodeBefore($source, $target)
    moveNodeAfter($source, $target)
    and maybe
    moveNodeUp($source)

  4. ivan Says:

    thanks for comments and proposal. I’m working on move methods and I’ll post them latter

  5. S?bastien Cramatte Says:

    I’ve got a fully funcional nested set class for ZF
    I’ve ported it from Cake.

    I would be nice to write a proposal to ZF and join our job !

    Take a look to this project …
    http://www.zym-project.com/

    Contact me by mail If you are interested

  6. Nested Sets mit Zend_Db_Table : zf-blog.de - Ein Weblog rund um das Zend Framework Says:

    […] in die Ideologie des Zend Frameworks passt, hat sich ein Entwickler kleine M?he gemacht und eine Nested Sets Erweiterung f?r die Zend_Db_Table geschrieben. Um eigene Nested Sets zu entwickeln kann man diese Nested Sets […]

  7. Nested Sets mit dem Zend Framework realisieren » Ralfs PHP und Zend Framework Blog Says:

    […] auf den Blog von Ivan Iordanov, welcher seine Erweiterung zu Zend_Db vorstellt, mit der man Nested Sets mit dem Zend Framework umsetzen kann. Dort findet man sowohl den kompletten Code als auch ein […]

Leave a Reply