namespace BlogController;
use LaminasMvcControllerAbstractActionController;
use LaminasViewModelViewModel;
use LaminasViewModelJsonModel;
class PostController extends AbstractActionController {
public function __construct(private PostTable $postTable) {}
public function indexAction(): ViewModel {
return new ViewModel([
"posts" => $this->postTable->fetchAll(),
]);
}
public function viewAction(): ViewModel {
$id = (int) $this->params()->fromRoute("id", 0);
$post = $this->postTable->getPost($id);
return new ViewModel(["post" => $post]);
}
public function addAction() {
$form = new PostForm();
$request = $this->getRequest();
if ($request->isPost()) {
$post = new Post();
$form->setInputFilter($post->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$post->exchangeArray($form->getData());
$this->postTable->savePost($post);
return $this->redirect()->toRoute("blog");
}
}
return new ViewModel(["form" => $form]);
}
// JSON response
public function apiAction(): JsonModel {
return new JsonModel(["posts" => $this->postTable->fetchAll()->toArray()]);
}
}