Question

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?

Was it helpful?

Solution

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;
    }
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top