-1

我厌倦了基于页面和所有内容制作脚本。我不想用旧的方式做事。我想学习基于 url 的 OOP。我知道如何使用 .htacces 进行 url 屏蔽和重写规则。但问题是,当我将所有查询转发到 PHP 页面时,我必须使用 switch case 语句来包含文件。就像查询是 p=profile 一样,我需要手动或按函数包含 profile.php 文件。但我不想做这种事情。我想学习专业的 PHP,这样我就可以创建诸如 wordpress 和 elgg 之类的 web 应用程序。我已经尝试查找有关它的在线教程,但它对我不起作用。

我希望至少有一个人能帮助我正确的方法。

4

3 回答 3

4

有很多方法可以做到这一点。它的要点是,在命名控制器及其方法时使用约定。使用 URL 重写将所有请求映射到单个请求调度程序,然后在该类中进行逻辑以加载适当的资源(如您所述)。但不要使用 Giant switch,而是执行以下操作:

  1. 请求的网址: http: //my.host.com/blog/hello-world
  2. 将 URL 重写为:dispatcher.php?q=blog/hello-world
  3. 在调度程序中,解析q并考虑: a) 类是否controllers/Blog.php存在?如果是这样实例化 b)helloWorld方法的类博客吗?如果是这样,调用它

这是一个脑残的例子,但也许它会让你开始。

我的建议:不要重新发明轮子。使用像 Laravel 或 Yii 或_这样的高质量框架(在此处插入最喜欢的框架)。这将为您节省大量时间。但如果你想或必须从头开始编写,请考虑下载这样的框架并通过示例学习。

于 2014-03-01T00:40:22.027 回答
2

通常,url 中的参数用于调用相应的class/function. 假设我们有这些网址:

  • example.com/index.php?控制器= foo
  • example.com/index.php?控制器= foo &功能=编辑
  • example.com/index.php?控制器=酒吧

index.php你可以开始玩包括如下:

$controller = $_GET["controller"];
include("controllers/{$controller}");
$theClass = new $controller();

某些 Web 应用程序使用“默认功能”,当 url 中未指定功能时触发该功能。例如,一个index函数:

$function = $_GET["function"];
if (empty($function))
    $function = "index";  // the default function to be called

$theClass->$function();

Foo 类可以如下所示:

class Foo{

    function index(){
        echo "hello index";
    }


    function edit(){
        echo "editing foo";
    }

}
  • 对于 url example.com/index.php?controller=foo的输出将是hello index
  • 对于 url example.com/index.php?controller=foo&function=edit输出将是editting foo

注意: 您可以改为使用$_SERVER['QUERY_STRING']$_GET使 url 更“友好”。

于 2014-03-01T00:42:52.223 回答
1

怎么样 :

<?php

if(!isset($_GET['page'])){$_GET['page'] = 'index';}
$whiteList = array('index', 'page1', 'page2');

$controller = in_array($_GET['page'], $whiteList) ? $_GET['page'] : 'index';

$controller = new $controller();
$controller::indexAction();

?>

编辑:添加了对控制器的调用。

于 2014-03-01T00:40:15.707 回答