处理页面切换的最佳方法是什么?


What is the best way to handle page switching?

目前我简单地使用switch($_GET['page'])。这是一个简单的解决方案,基本上适用于任何地方。

然而,遗憾的是,一些项目已经增长了这么多,我想知道,如果有一个更好的…更快的方法?

这是我目前如何切换页面的基础:

// There is more complex .htacces to translation of friendly-urls behind it, but for example sake, these variables are being produced:
$lext = array(
    'parent_page' => 'about-us',
    'child_page' => 'map-to-somewhere',
    'child_id' => NULL, // if it would be a article or something, it would be example.com/{parent_page}/{child_id}-some-friendly-url.html
);
switch ($lext['parent_page']) {
    case 'about-us':
        // about us page
    break;
    case '':
        // home
    break;
    default:
        // 404
    break;
}

在switch案例中,它要么触发一个函数,要么包含一个文件。因为它产生最快的页面加载结果。

所以我想知道,对于大量的流量和你的"index.php"aka。登陆文件点击率很高。最快最简单的解决方案是什么?
既然最简单或最愚蠢的解决方案似乎都能产生最好的结果,如果:

if ($lext['parent_page'] == 'about-us') {
    // about us page
} else if ($lext['parent_page'] == '') {
    // home
} else {
    // 404
}

. .将比switch()更快,性能更好。

我已经搜索了SO类似的问题,并测试了所有的答案,但我找到的那些,并没有表现得更好。

有很多答案。很大程度上取决于你的项目和你想要做多少重构。我关心的不是速度,而是代码的可伸缩性和易于维护。与if-else或其他方法相比,switch与许多情况相比可能不会导致任何明显的减速。

一种方法可能是进入MVC框架的世界,它通常每个页面都有一个控制器方法,允许您在代码中进行漂亮、干净的分割。例如,使用代码点火器,您可以这样指定页面:

class MySite {
    /* constructor etc */
    public function page_1() {
        //this is called on visits to /page_1
        //load a view for this page, etc
    }
    public function page_13() {
        //this is called on visits to /page_3
        //load a view for this page, etc
    }
}

更简单的方法可能是创建一个JSON数据文件,其中包含可用的案例以及每个案例中应该发生的情况。

{
    "page_1": {"inc": "page_1.php"},
    "page_13": {"func:": "some_func"},
}

然后,在PHP中:

//get data
$data = @file_get_contents($fp = 'pages_data.txt') or die("Couldn't load ".$fp);
$data = json_decode($data, 1);
//look for requested page in data - if found, include file or run function...
if (isset($data[$lext['parent_page']])) {
    $item = $data[$lext['parent_page']];
    //...include file
    if (isset($item['inc']) && file_exists($item['inc']))
        include $item['inc'];
    //...run function
    else if (isset($item'func']) && function_exists($item['func']))
        $item['func']();
} else
    //404...
}

这取决于你如何管理你的页面。如果您必须require每个页面文件,那么您总是可以加载该文件,只需:

$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'index';
if (file_exists(__DIR__.'/views/'.$page.'.php')) {
    require(__DIR__.'/views/'.$page.'.php');
} else {
   switch ($page) {
       // Custom rules that does not fit to previous rule.
   }
}

我建议使用类/动作结构来动态加载请求的页面(像大多数框架一样)。

[index.php]
$route = isset($_REQUEST['route']) ? $_REQUEST['route'] : 'index';
$page = explode('/', $route);
require_once(__DIR__.'/controller/'.ucfirst($route[0]).'Controller.php');
$className = ucfirst($route[0]).'Controller';
$class = new $className();
$class->{$route[1]}();
一些警告

总是尝试将请求列入白名单,不要忘记空值默认值,如果您可能通过POST或GET传递路由信息,请使用$_REQUEST


对于SEO Url,您将使用.htaccess和数据库。