简体   繁体   中英

Zend framework (zf2) how the input values are passed to the model?

This may be a very simple question about ZF2, but I can't get my head around it. So please bear with me.

Suppose I create a user registration form. It has 2 inputs: username and password. In the model, I create a class User that has $username and $password variables, and the setters + getters for the two variables.

My question is how to pass what a user writes into the HTML inputs to the corresponding setters? Obviously, it has to do with the $_POST array. But how is it done internally in ZF2? What should I use to pass the username input to the actual $username variable?

If your form is posting, the values will be stored within the post with the input ids as the keys. You can use a couple of ways to access them from there.

$this->getRequest()

Will get everything, then you can use ->getParams() to get all the post parameters or even ->getParam('username') to get just the ones you need.

You will need to use a hydrator to populate the model's data. An example would be Zend\\Stdlib\\Hydrator\\ClassMethods which accepts an array (such as the post data) and calls the setters of the target object.

$hydrator = new \Zend\Stdlib\Hydrator\ClassMethods;
$user     = new \User\Model\User;

$data = [
   'username' => 'foo',
   'password' => 'bar',
];

$hydrator->hydrate($data, $user);

echo $user->getUsername(); // foo

Keep in mind however that you will need to ensure that you sanitize all user supplied data (eg hash the password) as well as validate the form data is correct (eg ensure a minimum complexity of the password, or to ensure valid e-mail address for the username).

The Zend\\Form component is designed to integrate all these requirements as well as allow you to construct the forms HTML output. You would attach the hydrator to the form and once is has been validated you can retrieve a constructed entity populated will the user supplied data using $form->getData() .

$request = $this->getRequest();

if ($request->isPost()) {

    $form->setData($request->getPost());

    if ($form->isValid()) {

        // hydration occurs internally and returns our user populated
        $user = $form->getData(); 

        if ($user instanceof User) {
            echo $user->getUsername();
        }
   }
}

The ZF2 tutorial gives a detailed explanation of the process , if you have not already created the example project I highly recommend doing so.

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