View Single Post
Old 01-05-2006, 06:19 AM   #11 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 704
DJMaze is on a distinguished road
Class members can be overloaded to run custom code defined in your class by defining specially named methods (__set, __get, __call).
This is not adviced to use since it doesn't handle class inside class and it slows down your scripts.

However it can be used as nice factory system. The trick here is that you can make a factory of methods that you don't need often or need to be loaded before some script execution but not used unless certain actions are triggerd.

For an example you have a script that offers a HTML output template system but, one of your pages outputs RSS then it's useless to load the template class.
Instead you could use a factory with overloaders and that way the template is only loaded when it's realy needed to increase speed.

PHP Code:
<?php
class My_Handler
{
    protected 
$class_file;
    protected 
$class_name;
    protected 
$class_inst;

    public function 
__construct($class_name)
    {
        
$this->class_name $class_name;
        
$this->class_inst null;
    }

    public function 
__call($method$args)
    {
        if (!
$this->class_inst$this->load_inst();
        
$count count($args);
        if (
$count == 0) {
            return 
$this->class_inst->$method();
        } else if (
$count == 1) {
            return 
$this->class_inst->$method($args[0]);
        } else if (
$count == 2) {
            return 
$this->class_inst->$method($args[0], $args[1]);
        } else {
            
$call[0] =& $this->class_inst;
            
$call[1] = $method;
            return 
call_user_func_array($call$args); # this is slow
        
}
    }

    public function 
__get($nm)
    {
        if (!
$this->class_inst$this->load_inst();
        
$this->class_inst->$nm;
    }
    public function 
__set($nm$val)
    {
        if (!
$this->class_inst$this->load_inst();
        
$this->class_inst->$nm $val;
    }

    public function 
name() { return $this->class_name; }

    
# Check if class is already loaded else load it into memory
    
private function load_inst()
    {
        if (
$this->class_inst) return;
        
$file strtolower($this->class_name).'.php';
        if (!
class_exists($this->class_namefalse) && !file_exists($file)) {
            throw new 
Exception("Class {$this->class_name} does not exist");
        }
        require_once(
$file);
        
$this->class_inst = new $this->class_name($this);
    }

}

$template My_Handler($template);

if (
$_GET['rss']) {
    echo 
'rss'# template class NOT loaded
} else {
    
$template->include('index.html'); # template class gets loaded
    
$template->display();
}
DJMaze is offline   Reply With Quote