标签:
In the previous chapter we‘ve come to learn how we can use the zend-form and zend-db components for creating new data-sets. This chapter will focus on finalizing the CRUD functionality by introducing the concepts for editing anddeleting data.
The one fundamental difference between our "add post" and "edit post" forms is the existence of data. This means we need to find a way to get data from our repository into the form. Luckily, zend-form provides this via a data-bindingfeature.
In order to use this feature, you will need to retrieve a Post
instance, and bind it to the form. To do this, we will need to:
WriteController
on our PostRepositoryInterface
, from which we will retrieve our Post
.WriteController
, editAction()
, that will retrieve aPost
, bind it to the form, and either display the form or process it.WriteControllerFactory
to inject the PostRepositoryInterface
.We‘ll begin by updating the WriteController
:
PostRepositoryInterface
.PostRepositoryInterface
.PostRepositoryInterface
.editAction()
implementation.The final result will look like the following:
<?php
// In module/Blog/src/Controller/WriteController.php:
namespace Blog\Controller;
use Blog\Form\PostForm;
use Blog\Model\Post;
use Blog\Model\PostCommandInterface;
use Blog\Model\PostRepositoryInterface;
use InvalidArgumentException;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class WriteController extends AbstractActionController
{
/**
* @var PostCommandInterface
*/
private $command;
/**
* @var PostForm
*/
private $form;
/**
* @var PostRepositoryInterface
*/
private $repository;
/**
* @param PostCommandInterface $command
* @param PostForm $form
* @param PostRepositoryInterface $repository
*/
public function __construct(
PostCommandInterface $command,
PostForm $form,
PostRepositoryInterface $repository
) {
$this->command = $command;
$this->form = $form;
$this->repository = $repository;
}
public function addAction()
{
$request = $this->getRequest();
$viewModel = new ViewModel([‘form‘ => $this->form]);
if (! $request->isPost()) {
return $viewModel;
}
$this->form->setData($request->getPost());
if (! $this->form->isValid()) {
return $viewModel;
}
$post = $this->form->getData();
try {
$post = $this->command->insertPost($post);
} catch (\Exception $ex) {
// An exception occurred; we may want to log this later and/or
// report it to the user. For now, we‘ll just re-throw.
throw $ex;
}
return $this->redirect()->toRoute(
‘blog/detail‘,
[‘id‘ => $post->getId()]
);
}
public function editAction()
{
$id =