简体   繁体   中英

MVC form data submission to controller

I am managing to deploy a very simple implementation, containing a registration form and for demonstration purposes, I have chosen to use the MVC pattern.

My slight issue is that when I press the submit button, I want the submitted data to be handled by the suitable method of the controller.

For instance:

within the view part, I declare the form like this :

<form action="controller/validate" method="post"/>

I am assuming that this is a routing-related thing, but I am curious whether another way can be suggested.

--

Regards,

Theo

A router can be as simple as a switch statement instead of a full blown router for the small sites:

switch($_SERVER['REQUEST_URI']) {
    case 'controller/validate':
        $view = new \Views\User\Registration();
        $controller = new \Controllers\UserRegistration($view);
        $method = 'validate';
        break;

    default:
        $view = new \Views\Error\NotFound();
        $controller = new \Controllers\Error($view);
        $method = 'notFound';
        break;
}

echo $controller->$method();

Also note that instead of doing a relative URL based on the current path you often really want to do a relative URL to the document root:

<form action="/controller/validate" method="post"/>

Note the leading slash.

The above is just a simple (untested) example of semi pseudocode

Usually, you would make your controller accessible through a route (like POST /register ). A controller action is assigned to this route in a bootstrap file. Some pseudo-code:

$framework->route('GET', '/register',
                  'RegistrationController::action_form');
$framework->route('POST', '/register',
                  'RegistrationController::action_submit');

Another aproach would be mapping routes directly to controllers (some frameworks do this, I believe Kohana is one of them) like this:

  • Route: /register/submit
  • Resolves to: RegisterContoller::action_submit()
  • Management of request method ( GET , POST , PUT , DELETE in standard HTTP) happens in the action methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM