PHP framework development step 1-factory mode almost all PHP frameworks use the single-entry file mode, that is, all requests are transferred from index. php. The factory model must be used to distribute requests.
For example, when we request a URL like this:
http://www.test.com/index.php?c=User&a=index
It means that we need to request the index method of the User controller. In other words, index. php needs to create an instance of the User controller according to the parameters and call the index method. It seems to have implemented a "factory" function.
We can implement a factory class like this:
class Factory{public static function getInstance($controller_name,$action_name){if(class_exists($controller_name)){$controller = new $controller_name;if(method_exists($controller,$action_name)){$controller->$action_name();}else{exit('action not found');}}else{exit('controller not found');}}}
With this factory class, we can complete all the logic by writing the following code in index. php:
$controller_name = $_GET['c'];$action_name = $_GET['a'];Factory::getInstance($controller_name,$action_name);
Analyze the code above, first receive the controller name and method name, and pass it to the getInstance method of the Factory class Factory. Factory will automatically instantiate the controller and call the corresponding method.
This is the factory class. give some parameters to help you do the rest of the work.
Let's take a look at how the factory class is implemented. It first checks whether the controller class exists:
class_exists($controller_name);
If the class does not exist, the following message is displayed: controller not found.
Then, an instance of the controller is created, and the method is checked and executed.
method_exists($controller,$action_name);
This is the implementation principle of the factory class. of course, we can continue to improve it.
In more cases, we will place the controller in an independent file. in this case, the factory class needs to first introduce the controller file:
require('app/controller/'.$controller_name.'.php');