views:

234

answers:

2

I am fairly new to OO programming...

I am building what will eventually turn out to be a large library of classes to be used throughout my site. Clearly, loading the entire library on every page is a waste of time and energy...

So what I would like to do is require a single "config" php class file on each page, and be able to "call" or "load" other classes as needed - thus extending my class according to my needs.

From what I know, I can't use a function in the config class to simply include() other files, because of scope issues.

What are my options? How do developers usually handle this problem, and what is the most stable?

+2  A: 

Sound like you want autoload and spl_autoload_register if you are using classes from 3rd party libraries.

Glass Robot
+1  A: 

You can use __autoload() or create an Object Factory that will load the files required when you need them.

As an aside, if you're having scope issues with your library files, you should probably refactor your layout. Most libraries are sets of classes that can be instantiated in any scope.

The following is an example very basic object factory.

class ObjectFactory {

    protected $LibraryPath;

    function __construct($LibraryPath) {
     $this->LibraryPath = $LibraryPath;
    }

    public function NewObject($Name, $Parameters = array()) {
     if (!class_exists($Name) && !$this->LoadClass($Name))
      die('Library File `'.$this->LibraryPath.'/'.$Name.'.Class.php` not found.');
     return new $Name($this, $Parameters);
    }

    public function LoadClass($Name) {
     $File = $this->LibraryPath.'/'.$Name.'.Class.php'; // Make your own structure.
     if (file_exists($File))
             return include($File);
     else    return false;
    }
}

// All of your library files should have access to the factory
class LibraryFile {

    protected $Factory;

    function __construct(&$Factory, $Parameters) {
     $this->Factory = $Factory;
    }
}
sirlancelot
is there a tutorial anywhere that gives good tips on setting up a class library?
johnnietheblack
I added an example object factory.
sirlancelot