Are protected constructors considered good practice?
- by Álvaro G. Vicario
I'm writing some little helper classes to handle trees. Basically, I have a node and a special root node that represents the tree. I want to keep it generic and simple. This is part of the code:
<?php
class Tree extends TreeNode{
public function addById($node_id, $parent_id, $generic_content){
if( $parent = $this->findNodeById($parent_id) ){
$parent->addChildById($node_id, $generic_content);
}
}
}
class TreeNode{
public function __construct($node_id, $parent_id, $generic_content){
// ...
}
protected function addChildById($node_id, $generic_content){
$this->children[] = new TreeNode($this->node_id, $node_id, $generic_content);
}
}
$Categories = new Tree;
$Categories->addById(1, NULL, $foo);
$Categories->addById(2, NULL, $bar);
$Categories->addById(3, 1, $gee);
?>
My questions:
Is it sensible to force TreeNode instances to be created through TreeNode::addById()?
If it's so, would it be good practise to declare TreeNode::__construct() as private/protected?