10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 18: Hierarchical Data 277<br />

Nested Set<br />

Introduction<br />

Nested Set is a solution for storing hierarchical data that provides very fast read access.<br />

However, updating nested set trees is more costly. Therefore this solution is best suited for<br />

hierarchies that are much more frequ<strong>en</strong>tly read than writt<strong>en</strong> to. And because of the nature of<br />

the web, this is the case for most web applications.<br />

For more detailed information on the Nested Set, read here:<br />

• http://www.sitepoint.com/article/hierarchical-data-database/2 33<br />

• http://dev.mysql.com/tech-resources/articles/hierarchical-data.html 34<br />

Setting Up<br />

To set up your model as Nested Set, you must add some code to the setUp() method of your<br />

model. Take this Category model below for example:<br />

// models/Category.php<br />

Listing<br />

18-1<br />

class Category ext<strong>en</strong>ds <strong>Doctrine</strong>_Record<br />

{<br />

public function setTableDefinition()<br />

{<br />

$this->hasColumn('name', 'string', 255);<br />

}<br />

}<br />

public function setUp()<br />

{<br />

$this->actAs('NestedSet');<br />

}<br />

Here is the same example in YAML format. You can read more about YAML in the YAML<br />

Schema Files (page 195) chapter:<br />

---<br />

# schema.yml<br />

Listing<br />

18-2<br />

# ...<br />

Category:<br />

actAs: [NestedSet]<br />

columns:<br />

name: string(255)<br />

Detailed information on <strong>Doctrine</strong>'s templating model can be found in chapter 16 Behaviors<br />

(page 239). These templates add some functionality to your model. In the example of the<br />

nested set, your model gets 3 additional fields: lft, rgt and level. You never need to care<br />

about the lft and rgt fields. These are used internally to manage the tree structure. The<br />

level field however, is of interest for you because it's an integer value that repres<strong>en</strong>ts the<br />

depth of a node within it's tree. A level of 0 means it's a root node. 1 means it's a direct child<br />

33. http://www.sitepoint.com/article/hierarchical-data-database/2<br />

34. http://dev.mysql.com/tech-resources/articles/hierarchical-data.html<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!