In this section, we will provide an example of how you can use filters and/or validators in your controller to transform and check the data extracted from GET and/or POST variables.
Let's assume we implement a payment gateway system and need to create a web page displaying
a payment history for the given credit card on given date. This page can be handled by some
paymentHistoryAction()
action of a controller class, and the credit card number and date will
be extracted from GET variables. For the paymentHistoryAction()
method,
we need to implement some security checks:
Below, you can find the code of the action method:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Filter\StaticFilter;
use Zend\Validator\StaticValidator;
class IndexController extends AbstractActionController
{
// An action which shows the history of a credit
// card operations on certain date.
public function paymentHistoryAction()
{
// Get parameters from GET.
$cardNumber = (string)$this->params()->fromQuery('card', '');
$date = (string)$this->params()->fromQuery('date', date("Y-m-d"));
// Validate credit card number.
$isCardNumberValid = StaticValidator::execute($cardNumber, 'CreditCard');
if(!$isCardNumberValid) {
throw new \Exception('Not a credit card number.');
}
// Convert date to the right format.
$date = StaticFilter::execute($date, 'DateTimeFormatter',
['format'=>'Y-m-d']);
// The rest of action code goes here...
return new ViewModel();
}
}
Inside the action method, we use the params()
controller plugin (lines 16-17) to retrieve two
variables from $_GET
super-global array: the card
variable (credit card number) and the date
variable (the date).
In line 20, we validate the credit card number with the help of the CreditCard
validator.
If the card number is not acceptable, we throw an exception indicating an error (line 22).
In line 26, we use the DateTimeFormatter
filter to convert the date to the right format.