Forum Moderators: coopster

Message Too Old, No Replies

php - need help with log

         

zamrg

6:48 pm on Mar 9, 2009 (gmt 0)

10+ Year Member



I haven't really done too much OOP in php5 but I've had to start on a recent project and would like to take advantage of it.

I have a database table, for sake of simplicity lets say it's a table of categories which is filled with the following data: Dog, Cat, Mouse and Sheep. The app has an abstract class Animal and 4 child classes which extend it; Dog, Cat, Mouse and Sheep. The parent and child classes all have the same constructor parameters. The script then reads each category from the database and instantiates the child class based on the category name.

eg: (pseudocode)
read categories from database
foreach category {
if category = Dog, return new Dog('arg1', 'arg2', 'arg3', etc)
if category = Cat, return new Cat('arg1', 'arg2', 'arg3', etc)
if category = Mouse, return new Mouse('arg1', 'arg2', 'arg3', etc)
if category = Sheep, return new Sheep('arg1', 'arg2', 'arg3', etc)
...etc, etc
}

What would be the simplest and best way to instantiate the child classes based on the category name?

I've tested a switch statement, but it looks stupid and repetitive since their are 10+- categories an therefore 10+- child classes. I've also tried php's newish reflection methods, but this feels a bit erky.

any suggestions?

coopster

2:07 pm on Mar 11, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, zamrg.

How about using the category value to check for the existence of a class definition of the very same and create an instance upon success? Upon failure, throw an error or something, but handle accordingly.

zamrg

2:22 pm on Mar 11, 2009 (gmt 0)

10+ Year Member



hi coopster, and thanks for the welcome :)

I've actually been a member here for a while but couldn't for the life of me remember my last username or e-mail address.

I was helped by a member of another forum who pointed me to the Factory pattern at [php.net...]

I was unaware that you could do something like this:
eg:
$classname = 'MXRecord';
$class = new $classname('', '', '', etc);

but it seems to have solved this problem.

thanks for the assistance.

[edited by: coopster at 2:28 pm (utc) on Mar. 11, 2009]
[edit reason] removed period so link works [/edit]

coopster

2:27 pm on Mar 11, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Yep, that is what I was referring. The only thing you might want to add there is a try/catch block as you never know if you actually have the "classname" class defined before you add a new category to your database table. If you forgot to define it, at least you could throw yourself an error and handle accordingly.