Almost all PHP frameworks use a single-entry file approach, meaning that all requests are entered from index.php. It is necessary to use the Factory mode to achieve the requested distribution.
For example, we are requesting such a URL:
Http://www.test.com/index.php?c=User&a=index
The implication is that we need to request the user controller's index method. This means that index.php needs to create an instance of the user controller based on the parameters and call the index method. It seems to be the realization of 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 only need to write the following code in index.php to complete the logic:
$controller _name = $_get[' C '); $action _name = $_get[' a ']; Factory::getinstance ($controller _name, $action _name);
Analyze the above code, first receive the controller name and method name, passed to the factory class factory getinstance method. Factory automatically helps us instantiate the controller and invoke the appropriate method.
This is the factory class, give him some parameters, it can help you do the rest of the work.
Let's see how the factory class is implemented. It first checks to see if the controller class exists:
Class_exists ($controller _name);
If the class does not exist, you will be prompted: Controller not found.
It then creates an instance of the controller and then checks to see if the method exists and executes.
Method_exists ($controller, $action _name);
This is the factory class implementation principle, of course, can continue to improve it.
In more cases, we will put the controller in a separate file, when the factory class needs to first introduce the controller file:
Require (' app/controller/'. $controller _name. php ');
The first step in PHP framework development--Factory mode