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?
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?