Zend Method Route

What is a Method Route?

A Method Route allows you to restrict the route to specific HTTP methods (like GET, POST, PUT, etc.). This is useful when you want to create different logic for different HTTP methods on the same URL path.


Use Case:

You want:

  • /form to render a form when visited via GET
  • /form to process submission when submitted via POST


Syntax Pattern

'type' => \Laminas\Router\Http\Method::class,
'options' => [
  'verb' => 'GET' // or 'POST', 'PUT', etc.
]

Full Example

Step 1: Route Configuration (module/Application/config/module.config.php)

'router' => [
  'routes' => [
    'form-get' => [
      'type'  => \Laminas\Router\Http\Method::class,
      'options' => [
        'verb' => 'GET',
        'route' => '/form',
        'defaults' => [
          'controller' => Controller\MainController::class,
          'action'   => 'show',
        ],
      ],
    ],
    'form-post' => [
      'type'  => \Laminas\Router\Http\Method::class,
      'options' => [
        'verb' => 'POST',
        'route' => '/form',
        'defaults' => [
          'controller' => Controller\MainController::class,
          'action'   => 'submit',
        ],
      ],
    ],
  ],
],

Step 2: Controller Setup (module\Application\src\Controller\MainController.php)

namespace Application\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;

class MainController extends AbstractActionController
{
  public function showAction()
  {
    return new ViewModel();
  }

  public function submitAction()
  {
    $post = $this->getRequest()->getPost();
    return new ViewModel(['data' => $post]);
  }
}

Step 3: View Files

view/application/main/show.phtml

<h2>Contact Form</h2>
<form method="post" action="/form">
  Name: <input type="text" name="name"><br>
  <input type="submit" value="Submit">
</form>


view/application/main/submit.phtml

<h2>Form Submitted</h2>
<p>Name: <?= $this->data['name'] ?? 'Not provided' ?></p>

Access in Browser

URL

Matched

Action Triggered

Untitle

/form

GET

showAction()

show.phtml

/form

POST

submitAction()

submit.phtml


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.