Page 1 of 1

Two simple designs, which is better?

Posted: Fri Oct 27, 2006 5:35 am
by Ollie Saunders
The actual functionality here is really trivial. I'm pretty sold on ChoiceB now. But having prepared this post, here it is anyway.

What both of these do is to provide an interface to an array of classes. Classes as in the HTML attribute:

Code: Select all

<div class="">
^ that kind of class, a CSS class.
You can, add, remove and parse from a string. Please note the code itself is untested.

ChoiceA

Code: Select all

class ChoiceA
{
    private $_classes;
    public function __get($name)
    {
        if ($name == 'class') {
            return implode(' ', $this->_classes);
        }
    }
    public function __set($name, $value)
    {
        if ($name == 'class') {
            $this->_classes = preg_split('/\s+/', trim($value));
        }
    }
    public function addClass($toAdd)
    {
        $this->_classes[] = removeAllWhitespace($toAdd);
    }
    public function removeClass($toAdd)
    {
        $result = array_search($toAdd, $this->_classes);
        if ($result !== false) {
            $this->_classes[$result] = null;
        }
    }
}
/**** USAGE ******/
$div = new ChoiceA;
$div->class = 'foo bar';
$div->addClass('zim');
// $div->class == 'foo bar zim';
$div->removeClass('bar');
// $div->class == 'foo zim';
ChoiceB

Code: Select all

class ChoiceB
{
    private $_classes;
    public function __construct()
    {
        $this->_classes = new HtmlClassManager;
    }
    public function __get($name)
    {
        if ($name == 'class') {
            return $this->_classes;
        }
    }
    // no __set
}
class HtmlClassManager
{
    private $_classes;
    public function add($class)
    {
        $this->_classes[] = $class;
    }
    public function remove($class)
    {
        $result = array_search($toAdd, $this->_classes);
        if ($result !== false) {
            $this->_classes[$result] = null;
        }
    }
    public function set($classes) // just an alias
    {
        $this->parseFromString($classes);
    }
    public function parseFromString($classes)
    {
        $this->_classes = preg_split('/\s+/', trim($classes));
    }
    public function get()
    {
        return implode(' ', $this->_classes);
    }
}
/**** USAGE ******/
$div = new ChoiceB;
$div->class->parseFromString('foo bar');
$div->class->add('zim');
$div->class->remove('bar');
// $div->class->get() == 'foo zim';

Posted: Fri Oct 27, 2006 11:04 am
by feyd
The "B" path feels better from a quick once-over. It feels more compartmentalized, more object oriented.

Posted: Fri Oct 27, 2006 6:37 pm
by RobertGonzalez
I agree with feyd. It looks a little more resusable.

Posted: Sat Oct 28, 2006 3:46 am
by Ollie Saunders
Yep, good good.