I’m making a small PHP MVC framework for fun. I’m using a front controller index.php to route all traffic around and call new controllers as requested. However, I need a way to create an instance of a user generated controller base solely on the name of the controller (basically, the filename ie, controllers/posts.php).
Is there any way to do this?
There are a couple ways you can do this. One way is to establish a convention, such that the name of the class is based on the name of the file. Another way to do it would be to parse the file for the name of the class. Did you want to see some small code examples?
EDIT: Simple Example
Imagine we’re in some core MVC controller and we want to load a controller provided by a third party user. There are 2 things you need to do:
Suppose you have a convention such as Zend where class names map to the filesystem so a controller might be
MyProject/Controller/Login.phpfor the path to the login controller, relative to the root of the project. Following the Zend convention, the name of the class would be
MyProject_Controller_Login. If you want to instantiate this class all you have to do is:If you need to instantiate the class based on runtime data, you can do so with a variable that holds the name of the class, so
Hopefully that’s enough to get you rolling; let me know if you need more.