好的,所以我一直在考虑为特定市场开发自己的自定义 CMS 系统,并且我一直在研究一些框架,我遇到的问题是它们不能自动路由。在 laravel 中,如果我没记错地响应这样的 url,你会做这样的事情:
Route::get('/user', function()
{
return "This is a user";
});
这基本上会监听一个特定的请求。现在我简化这个的想法是创建一个自动路由器。所以我所做的是设置一个 .htaccess 文件,它接受每个请求并将其定向到 index.php。它还在 .com 之后接受了任何内容,因此类似于www.testsite.com/admin/pages/edit/5
并将其附加为 get 变量。
所以在上面的例子中,我传递了一个请求的四个参数:
admin - request path / used to signify a login check must be done before passing
them on to their request
pages - This would be the class or object
edit - This would be the method called from the class / object
5 - This would be the actual row of the record in the database being edited
所以我开发了一个看起来像这样的路由器类:
class router {
public $url;
public $protectedPaths = array('admin','users','client');
public function __construct() {
$this -> url = explode('/', $_GET['url']);
if($this -> url[0] == '') {
$this -> loadDefaultView();
} else {
// Check to ensure that the path is not protected
if(in_array($this -> url[0], $this -> protectedPaths)) {
// check to ensure user is logged in
if($_COOKIE['isLogged']) {
// This means that there is no action or model needed just a returned view
if($this -> url[2] == '') {
$this -> loadViewWithoutAction();
} else {
// we check to ensure there is a controller
if(file_exists(baseControllers .'controller.'. $this -> url[1] .'.php')) {
// require that controller and instantiate it
require baseControllers .'controller.'. $this -> url[1] .'.php';
$obj = new $this -> url[1];
// check to see if method exists
if(method_exists($obj, $this -> url[2])) {
if($_POST) {
$data = $_POST;
} else {
$data = array($this -> url[3]);
}
// run method if necessary
$data = call_user_func_array(array($obj, $this -> url[2]), $data);
$this -> loadAdminView( $data );
} else {
$this -> loadErrorView();
}
} else {
$this -> loadErrorView();
}
}
} else {
header("Location: /auth/form");
}
} else {
// we check to ensure there is a controller
if(file_exists(baseControllers .'controller.'. $this -> url[0] .'.php')) {
// require that controller and instantiate it
require baseControllers .'controller.'. $this -> url[0] .'.php';
$obj = new $this -> url[0];
// check to see if method exists
if(method_exists($obj, $this -> url[1])) {
// run method if necessary
$data = call_user_func_array(array($obj, $this -> url[1]), array($this -> url[2]));
$this -> loadPublicView( $data );
} else {
$this -> loadErrorView();
}
} else {
$this -> loadErrorView();
}
}
}
}
所以我会使用许多不同的 if else 语句,也许还有一个 switch 来区分不同的请求等。最后我的问题是,自动加载一个类并运行一个方法是这种不好的做法。从我在框架中看到的情况来看,这都是手动的,我不是专家,所以我假设这可能是有原因的。此外,我几乎没有发现任何关于在 Web 上的 OOP 中自动执行 PHP 请求的内容。
我真的很想自动化这个,但同时我也不想引起安全问题。哦,对于用户输入的任何表格或个人信息,所有内容都将被发布或 ajax 以防止 url 被黑客入侵。
感谢您提前提供任何建议或答案!