【问题标题】:MVC - how to make the url not to change when a method is calledMVC - 如何在调用方法时使 url 不改变
【发布时间】:2012-03-11 04:16:38
【问题描述】:

我有

登录控制器、模型和视图

网址http://mySite/login

现在当我在http://mySite/controller 时,它会显示登录表单,然后当我提交表单时,会调用 run 方法,因此 url 会更改为 http://mySite/login/run

我怎样才能阻止这个:?

P.S // 我按照这个 tut 创建了自己的 MVC:http://www.youtube.com/watch?v=2Eu0Nkpo6vM

登录控制器

class Login extends Conroller  {

    function __construct() {
        parent::__construct();  
    }

    function index() 
    {   
        $this->view->render('authentication/enter');
    }

    function run()
    {
        $this->model->run();
    }


}

登录模式

class Login_Model extends Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function run()
    {

            $sth = $this->dbh->connect()->prepare("SELECT UserID FROM users WHERE 
                username = :login ");
        $sth->execute(array(':login' => $_POST['login']));

        $data = $sth->fetch();

        $count =  $sth->rowCount();
        if ($count > 0) {
            // login
            Session::set('loggedIn', $_POST['login']);
            header('location: ../dashboard');
        } else {
            echo 4;
        }


    }

}

使用 .htacces

网址是

http://mySite/index.php?url={控制器名称}

http://mySite/index.php?url={控制器名称}/{来自控制器的一些方法}

【问题讨论】:

  • 请展示您的一些代码,以便我们找出重定向的位置。
  • 总之,当你在 /index.php?url=login 加载登录控制器时,加载登录模型和视图。 Everthing 正在工作,但教程中显示了如何更改网址

标签: php model-view-controller oop


【解决方案1】:

没有观看整个视频,也没有想太多为什么要重新发明 PHP MVC 轮子,这是我的最佳猜测。

  1. 更改视图的表单以提交到索引操作

    <form method="post" action="login" ...
    
  2. 在您的索引操作中,检测 POST 请求并从那里运行模型的 run() 方法

    function index() 
    {   
        if ($this->request->isPost()) { // seriously, I'm just guessing here
            $this->model->run();
        }
        $this->view->render('authentication/enter');
    }
    

一些笔记...

  • 不要从模型中执行控制器任务(即重定向)
  • 在发送Location 响应标头后始终为exit;
  • 放下这个烂摊子,试试经过验证和测试的 MVC 框架,例如 Symfony 或 Zend

【讨论】:

  • oop 是的
  • @MarianPetrov 我现在喜欢 Symfony 2,但这只是我的看法
猜你喜欢
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 2016-08-14
相关资源
最近更新 更多