Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having the option of customized classes but a unified class name

Tags:

oop

php

Suppose you are building a web application that is going to be a packaged product one day, one that users will want to be able to extend and customize.

It comes with a core library consisting of PHP files containing classes:

/library/
/library/frontend.class.php
/library/filesystem.class.php
/library/backend.class.php

Now, suppose you want to keep a clean core that users can't patch. Still, you want the user to be able to customize every nut and bolt if need be.

My current idea is to create an autoloading mechanism that, when a class is instantiated, first loads the core include:

/library/frontend.class.php

then, it switches to the user directory and looks whether there is an include of the same name:

 /user/library/frontend.class.php

if one exists, it includes that as well.

Obviously, the user include must contain a class definition that extends the definition in the core include.

Now my question is, how would I instantiate such a class? After all, I can always be sure there is a definition of:

class frontend_core

but I can not be sure there is a

class frontend_user extends frontend_core

However, I would like to be able to rely on, and instantiate, one class name, regardless of whether there was a custom extension to the class or not.

Is there a clever way, idea, or pattern how to achieve this?

Of course, I could write a simple factory helper function that looks for the user class first and then for the core class and returns an initialized object, but I would really like to keep this as clean and simple as possible, because as I said, it is going to be a packaged product.

I am looking for a smart trick or pattern that uses as little code, and introduces as little new functionality, as possible.

like image 952
Pekka Avatar asked Mar 11 '10 13:03

Pekka


1 Answers

Why don't you follow the approach as used by Propel? You generate your base classes and already provide an empty User class (extending the base class) where your users can put their overrides/specific implementation details, and in your code you always refer to the User classes. So basically you just use the inverse of the logic you described.

If the explanation above isn't clear, check out http://propel.phpdb.org/trac/wiki/Users/Documentation/1.4/QuickStart#a6.UsingtheGeneratedSQLandOMFiles and generate code for a small database. The base classes are in the om folder, the (by default empty) user classes are in the root folder.

like image 159
wimvds Avatar answered Oct 16 '22 03:10

wimvds