1
0
mirror of synced 2025-02-01 13:01:45 +03:00

joesimms: added support for many roots for one table, added another example illustrating this, see EXAMPLE2.tree.php, also changed toString to __toString in getPath()

This commit is contained in:
joesimms 2007-01-11 14:17:21 +00:00
parent d829e223b2
commit 86ec08c331
7 changed files with 1028 additions and 659 deletions

View File

@ -39,9 +39,8 @@ class Menu extends Doctrine_Record {
} }
// this toString() function is used to get the name for the path, see node::getPath // this __toString() function is used to get the name for the path, see node::getPath
// maybe change to actually use __toString(), howvever, i wondered if this had any significance ?? public function __toString() {
public function toString() {
return $this->get('name'); return $this->get('name');
} }
} }

217
draft/EXAMPLE2.tree.php Normal file
View File

@ -0,0 +1,217 @@
<?php
/*please note that this is a very DRAFT and basic example of how you can use the different functions available in the tree implentation with many roots in one table*/
require_once("../lib/Doctrine.php");
// autoloading objects, modified function to search drafts folder first, should run this test script from the drafts folder
function __autoload($classname) {
if (class_exists($classname)) {
return false;
}
if (! $path) {
$path = dirname(__FILE__);
}
$classpath = str_replace('Doctrine_', '',$classname);
$class = $path.DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR,$classpath) . '.php';
if ( !file_exists($class)) {
return Doctrine::autoload($classname);
}
require_once($class);
return true;
}
// define our tree
class Menu extends Doctrine_Record {
public function setTableDefinition() {
$this->setTableName('menu_many_roots');
// add this your table definition to set the table as NestedSet tree implementation
// with many roots
$this->actsAsTree('NestedSet', array('has_many_roots' => true));
// you do not need to add any columns specific to the nested set implementation, these are added for you
$this->hasColumn("name","string",30);
}
// this __toString() function is used to get the name for the path, see node::getPath
public function __toString() {
return $this->get('name');
}
}
// set connections to database
$dsn = 'mysql:dbname=nestedset;host=localhost';
$user = 'user';
$password = 'pass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$manager = Doctrine_Manager::getInstance();
$conn = $manager->openConnection($dbh);
// create root
$root = new Menu();
$root->set('name', 'root');
$manager->getTable('Menu')->getTree()->createRoot($root);
// build tree
$two = new Menu();
$two->set('name', '2');
$root->getNode()->addChild($two);
$one = new Menu();
$one->set('name', '1');
$one->getNode()->insertAsPrevSiblingOf($two);
// refresh as node's lft and rgt values have changed, zYne, can we automate this?
$two->refresh();
$three = new Menu();
$three->set('name', '3');
$three->getNode()->insertAsNextSiblingOf($two);
$two->refresh();
$one_one = new Menu();
$one_one->set('name', '1.1');
$one_one->getNode()->insertAsFirstChildOf($one);
$one->refresh();
$one_two = new Menu();
$one_two->set('name', '1.2');
$one_two->getNode()->insertAsLastChildOf($one);
$one_two->refresh();
$one_two_one = new Menu();
$one_two_one->set('name', '1.2.1');
$one_two->getNode()->addChild($one_two_one);
$root->refresh();
$four = new Menu();
$four->set('name', '4');
$root->getNode()->addChild($four);
$root->refresh();
$five = new Menu();
$five->set('name', '5');
$root->getNode()->addChild($five);
$root->refresh();
$six = new Menu();
$six->set('name', '6');
$root->getNode()->addChild($six);
output_message('initial root');
output_tree($root);
// create a new root with a tree
$root2 = new Menu();
$root2->set('name', 'new root');
$manager->getTable('Menu')->getTree()->createRoot($root2);
// build tree
$two2 = new Menu();
$two2->set('name', '2');
$root2->getNode()->addChild($two2);
$one2 = new Menu();
$one2->set('name', '1');
$one2->getNode()->insertAsPrevSiblingOf($two2);
// refresh as node's lft and rgt values have changed, zYne, can we automate this?
$two2->refresh();
$three2 = new Menu();
$three2->set('name', '3');
$three2->getNode()->insertAsNextSiblingOf($two2);
$two2->refresh();
$one_one2 = new Menu();
$one_one2->set('name', '1.1');
$one_one2->getNode()->insertAsFirstChildOf($one2);
$one2->refresh();
$one_two2 = new Menu();
$one_two2->set('name', '1.2');
$one_two2->getNode()->insertAsLastChildOf($one2);
$one_two2->refresh();
$one_two_one2 = new Menu();
$one_two_one2->set('name', '1.2.1');
$one_two2->getNode()->addChild($one_two_one2);
$root2->refresh();
$four2 = new Menu();
$four2->set('name', '4');
$root2->getNode()->addChild($four2);
output_message('new root');
output_tree($root2);
$one_one->refresh();
$six->set('name', '1.0 (was 6)');
$six->getNode()->moveAsPrevSiblingOf($one_one);
$one_two->refresh();
$five->refresh();
$five->set('name', '1.3 (was 5)');
$five->getNode()->moveAsNextSiblingOf($one_two);
$one_one->refresh();
$four->refresh();
$four->set('name', '1.1.1 (was 4)');
$four->getNode()->moveAsFirstChildOf($one_one);
$root->refresh();
$one_two_one->refresh();
$one_two_one->set('name', 'last (was 1.2.1)');
$one_two_one->getNode()->moveAsLastChildOf($root);
output_message('transformed initial root');
output_tree($root);
function output_tree($root)
{
// display tree
// first we must refresh the node as the tree has been transformed
$root->refresh();
// next we must get the iterator to traverse the tree from the root node
$traverse = $root->getNode()->traverse();
output_node($root);
// now we traverse the tree and output the menu items
while($item = $traverse->next())
{
output_node($item);
}
unset($traverse);
}
function output_node($record)
{
echo str_repeat('-', $record->getNode()->getLevel()) . $record->get('name') . ' (has children:'.$record->getNode()->hasChildren().') '. ' (is leaf:'.$record->getNode()->isLeaf().') '.'<br/>';
}
function output_message($msg)
{
echo "<br /><strong><em>$msg</em></strong>".'<br />';
}

File diff suppressed because it is too large Load Diff

View File

@ -72,6 +72,8 @@ class Doctrine_Node_NestedSet_PreOrderIterator implements Iterator
} else { } else {
$query = $q->where("$componentName.lft > ? AND $componentName.rgt < ?", $params)->orderBy('lft asc'); $query = $q->where("$componentName.lft > ? AND $componentName.rgt < ?", $params)->orderBy('lft asc');
} }
$query = $record->getTable()->getTree()->returnQueryWithRootId($query, $record->getNode()->getRootValue());
$this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0; $this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0;
$this->options = $opts; $this->options = $opts;

View File

@ -39,7 +39,7 @@ class Doctrine_Tree
/** /**
* @param array $options * @param array $options
*/ */
protected $options; protected $options = array();
/** /**
* constructor, creates tree with reference to table and any options * constructor, creates tree with reference to table and any options
@ -88,4 +88,23 @@ class Doctrine_Tree
} }
return new $class($table, $options); return new $class($table, $options);
} }
/**
* gets tree attribute value
*
*/
public function getAttribute($name)
{
return isset($this->options[$name]) ? $this->options[$name] : null;
}
/**
* sets tree attribute value
*
* @param mixed
*/
public function setAttribute($name, $value)
{
$this->options[$name] = $value;
}
} }

View File

@ -43,7 +43,7 @@ interface Doctrine_Tree_Interface {
* *
* @return object $record instance of Doctrine_Record * @return object $record instance of Doctrine_Record
*/ */
public function findRoot(); public function findRoot($root_id = 1);
/** /**
* optimised method to returns iterator for traversal of the entire tree from root * optimised method to returns iterator for traversal of the entire tree from root

View File

@ -31,6 +31,21 @@
*/ */
class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Interface class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Interface
{ {
/**
* constructor, creates tree with reference to table and sets default root options
*
* @param object $table instance of Doctrine_Table
* @param array $options options
*/
public function __construct(Doctrine_Table $table, $options)
{
// set default many root attributes
$options['has_many_roots'] = isset($options['has_many_roots']) ? $options['has_many_roots'] : false;
$options['root_column_name'] = isset($options['root_column_name']) ? $options['root_column_name'] : 'root_id';
parent::__construct($table, $options);
}
/** /**
* used to define table attributes required for the NestetSet implementation * used to define table attributes required for the NestetSet implementation
* adds lft and rgt columns for corresponding left and right values * adds lft and rgt columns for corresponding left and right values
@ -38,6 +53,9 @@ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Int
*/ */
public function setTableDefinition() public function setTableDefinition()
{ {
if($this->getAttribute('has_many_roots'))
$this->table->setColumn($this->getAttribute('root_column_name'),"integer",11);
$this->table->setColumn("lft","integer",11); $this->table->setColumn("lft","integer",11);
$this->table->setColumn("rgt","integer",11); $this->table->setColumn("rgt","integer",11);
} }
@ -53,8 +71,13 @@ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Int
$record = $this->table->create(); $record = $this->table->create();
} }
// if tree is many roots, then get next root id
if($this->getAttribute('has_many_roots'))
$record->getNode()->setRootValue($this->getNextRootId());
$record->set('lft', '1'); $record->set('lft', '1');
$record->set('rgt', '2'); $record->set('rgt', '2');
$record->save(); $record->save();
return $record; return $record;
@ -65,11 +88,15 @@ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Int
* *
* @return object $record instance of Doctrine_Record * @return object $record instance of Doctrine_Record
*/ */
public function findRoot() public function findRoot($root_id = 1)
{ {
$q = $this->table->createQuery(); $q = $this->table->createQuery();
$root = $q->where('lft = ?', 1) $q = $q->where('lft = ?', 1);
->execute()->getFirst();
// if tree has many roots, then specify root id
$q = $this->returnQueryWithRootId($q, $root_id);
$root = $q->execute()->getFirst();
// if no record is returned, create record // if no record is returned, create record
if (!$root) { if (!$root) {
@ -93,9 +120,14 @@ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Int
// fetch tree // fetch tree
$q = $this->table->createQuery(); $q = $this->table->createQuery();
$tree = $q->where('lft >= ?', 1) $q = $q->where('lft >= ?', 1)
->orderBy('lft asc') ->orderBy('lft asc');
->execute();
// if tree has many roots, then specify root id
$root_id = isset($options['root_id']) ? $options['root_id'] : '1';
$q = $this->returnQueryWithRootId($q, $root_id);
$tree = $q->execute();
$root = $tree->getFirst(); $root = $tree->getFirst();
@ -142,4 +174,65 @@ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Int
// TODO: if record doesn't exist, throw exception or similar? // TODO: if record doesn't exist, throw exception or similar?
} }
/**
* fetch root nodes
*
* @return collection Doctrine_Collection
*/
public function fetchRoots()
{
$q = $this->table->createQuery();
$q = $q->where('lft = ?', 1);
return $q->execute();
}
/**
* calculates the next available root id
*
* @return integer
*/
public function getNextRootId()
{
return $this->getMaxRootId() + 1;
}
/**
* calculates the current max root id
*
* @return integer
*/
public function getMaxRootId()
{
$component = $this->table->getComponentName();
$column = $this->getAttribute('root_column_name');
// cannot get this dql to work, cannot retrieve result using $coll[0]->max
//$dql = "SELECT MAX(c.$column) FROM $component c";
$dql = "SELECT c.$column FROM $component c ORDER BY c.$column desc LIMIT 1";
$coll = $this->table->getConnection()->query($dql);
$max = $coll[0]->get($column);
$max = !is_null($max) ? $max : 0;
return $max;
}
/**
* returns parsed query with root id where clause added if applicable
*
* @param object $query Doctrine_Query
* @param integer $root_id id of destination root
* @return object Doctrine_Query
*/
public function returnQueryWithRootId($query, $root_id = 1)
{
if($this->getAttribute('has_many_roots'))
$query->addWhere($this->getAttribute('root_column_name') . ' = ?', $root_id);
return $query;
}
} }