An example of an MVC controller

后端 未结 6 543
有刺的猬
有刺的猬 2020-12-22 16:09

I have been reading a lot about how and why to use an MVC approach in an application. I have seen and understand examples of a Model, I have seen and understand examples of

6条回答
  •  梦毁少年i
    2020-12-22 17:01

    Request example

    Put something like this in your index.php:

    $actionName();
    

    Really basic, but you get the idea... (I also didn't take care of loading the controller class, but I guess that can be done either via autoloading or you know how to do it.)

    Simple controller example (controllers/login.php):

    request->get('username');
            $password = $this->request->get('password');
    
            $this->loadModel('users');
            if ($this->users->validate($username, $password))
            {
                $userData = $this->users->fetch($username);
                AuthStorage::save($username, $userData);
                $this->redirect('secret_area');
            }
            else
            {
                $this->view->message = 'Invalid login';
                $this->view->render('error');
            }
        }
    
        function logoutAction()
        {
            if (AuthStorage::logged())
            {
                AuthStorage::remove();
                $this->redirect('index');
            }
            else
            {
                $this->view->message = 'You are not logged in.';
                $this->view->render('error');
            }
        }
    }
    

    As you see, the controller takes care of the "flow" of the application - the so-called application logic. It does not take care about data storage and presentation. It rather gathers all the necessary data (depending on the current request) and assigns it to the view...

    Note that this would not work with any framework I know, but I'm sure you know what the functions are supposed to do.

提交回复
热议问题