It is easier to manage classes with its own file. If you create an email class then it should be saved in a file named mailer.php This class may need many other classes, the problem begins here. Now you must have to include all needed class files in the mailer file to work properly. But if you have a much bigger framework to work with, then it will be hard to manage the long list of file inclusion manually.

In PHP5 we have a solve for this problem. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

To properly use this __autoload function we have to manage a pattern to name the classes. First of all we have to manage the file and folder structure to follow the naming convension. Put your classes in “Classes” folder after grouping them in separate folders. Example – Say, you are creating a “Email” class which includes “Smtp”, “Pop”, “Imap” etc. So here all these classes can be grouped into a folder named “Mailer”. Thus the final destination of the “Email” class will be “Classes/Mailer/Email.php” which will be needed “Classes/Mailer/Smtp.php”, “Classes/Mailer/Pop.php”, “Classes/Mailer/Imap.php” etc. Now the class name will look just similar like its path name with the difference of slashes will be replaced by underscores. Example: The class name of “Classes/Mailer/Email.php” will be Classes_Mailer_Email
The class definition will be like -

class Classes_Mailer_Email
{
        // class body goes here
}

This will manage your code inclusion from any file. An easy example has been given in the attached file. The most important part in this example is the constant “DOCROOT”. DOCROOT represents the relative base/root path of the project folder in the server. The path string is relative with the current executing file. After defining the constant include the autoloader.php which will further handle the class inclusion part automatically.

If you have any problem with this naming convention, folder management or __autoload function please leave me a reply. I shall try to solve it as soon as possible. Here is a preview of the example -


Download Source Code

, , , , , , , ,