在面向对象的PHP中使用MVC时的控制器问题

时间:2011-01-05 17:56:29

标签: php model-view-controller search get

我目前正在使用面向对象的PHP中的MVC编写书店,我很难弄清楚控制器在处理请求时应该如何工作,特别是在处理表单时。

例如,我有一个搜索表单,当用户访问“index.php?action = search”时显示但是我不确定我应该如何处理表单中的搜索字符串,因为我无法发送“$ _GET” ['action'] =再次搜索“将”index.php?action?search = searchstring“发送到浏览器,以便显示搜索结果而不使用隐藏字段发送搜索操作,这当然非常不安全!!

我觉得这是太费力了,因为它的价值和进展似乎是迄今为止尝试这个的更好方法!除非你能说服我,否则!!

由于

3 个答案:

答案 0 :(得分:0)

嗯,在你的情况下,你应该使用额外的参数重定向。例如,使用index.php?action=search&q=searchstring。这将保留仅根据动作参数调用正确的“控制器”的能力。

至于“MVC”部分你是对的。这是网络应用的not overly applicable。但是你可以阅读Model-View-Presenter,它更像是每个人都在做的事情。

答案 1 :(得分:0)

使用此HTML完成index.php?action=search&q=WHATEVER没有任何问题:

<form method="GET" action="index.php">
<input type="hidden" name="action" value="search" />
Search: <input type="text" name="q" />
<!-- ... -->

这大约是搜索引擎如何做到这一点,除了他们使用URL重写来使URL更漂亮。例如,Bing搜索“test”是http://www.bing.com/search?q=test

当你第一次学习MVC时,MVC看起来很麻烦,但它确实是一种高效便捷的Web开发模式,远远优于程序风格的“随处可见”的web开发。

答案 2 :(得分:0)

你应该明白PHP中的MVC模式通常是这样的:

您有两个关键变量:

  • 方法

他们总是默认:

  • class = index
  • method = index

因此,当参数class传递到URI时,它会覆盖默认值,因此使用index.php?class=view上面的内容变为:

  • class = view
  • method = index

您可以运行类view.php并将视图类初始化为对象,并执行如下方法:

class View/*_Controller extends Controller*/
{
     public function index(){}
}

传递的任何其他变量都可以通过GET请求或POST获得。

您还应注意,这通常是通过网址语法中的URI处理的,因此以下index.php?action=view&method=download变为/view/download/

在将类/方法发送到方法之后,URI中的任何内容,例如下面的例子。

/view/download/id/browser

这将执行以下方法并在上下文中传递变量的值。

class View/*_Controller extends Controller*/
{
     public function download($id,$direction)
     {
     }
}

现在我知道这不是特定于您的问题,但我认为您对事情的看法不对,这应该可以帮助您开始将框架放入可管理的结构中。


更新

Controller使用路由器通过GET / POST初始化,路由器是一个从URI中检测类/方法的类,然后找到正确的控制器并执行它及其方法。

路由器的一个例子如下:

class Router
{
    //Params
    public $route;

    public static function CreateRoute($route = false)
    {
        return new Router($route);
    }

    public function __construct($route = false)
    {
         if($route !== false)
         {
              $this->route = $route;
         }else
         {
             $this->route = $_SERVER['REQUEST_URI'];
         }

         /*
             * The route would be parsed so that the following are matched
             * {/class}{/method}{/param1}{/param1}
             * /view/download/12/direct | as example
         */
    }


    public function run()
    {
        /*
            * Here you would do the following:
            * Validate the class to make sure no one is triggering an LFI
            * Make sure the class file exists within the directory
            * Include the class file and create an instance of it
            * Execute the method  sending in the params.
        */
    }
}

这样的用法:

$Route = Router::CreateRoute(); //AutoDetect
$Route->run();

看看下面的图片,可能会帮助您理解。 Codeigniter Application Flow Chart