Phalconで既存のプロジェクトにモジュールを追加する2
その1で作ったコメントモジュールを使って記事にコメントを行えるようにします。
記事の表示アクション
PostsControllerのviewアクションです。
モデル名とモデルIDでfindして結果をViewに渡します。
php
// app/controllers/PostsController.php
public function viewAction($id)
{
$post = Posts::findFirstById($id);
if (!$post) {
$this->flash->error("post was not found");
return $this->dispatcher->forward(array(
"controller" => "posts",
"action" => "index"
));
}
$comments = Comments::find(array(
'conditions' => array(
'model' => 'Posts',
'model_id' => $id
)
));
$this->view->setVars(array(
"post" => $post,
"comments" => $comments
));
}
記事のView
コメントの表示とコメントフォームを作成します。
formタグを閉じる部分はhtmlで書かないといけないみたいです‥
php
<!— app/views/posts/view.volt —>
{% for comment in comments %}
{{ comment.body}}
<br />
{% endfor %}
{{ form("comments/comments/create", "method":"post") }}
<input type="hidden" name="model" value="Posts"]]>
<input type="hidden" name="model_id" value="{{ post.id }}"]]>
{{ text_field("body", "type" : "date") }}
{{ submit_button("Comment") }}
</form>
コメント作成アクション
CommentsControllerのcreateActionはほぼScaffoldそのままですが、記事のページにリダイレクトします。
php
// app/modules/comments/controllers/CommentsController.php
public function createAction()
{
if (!$this->request->isPost()) {
return $this->dispatcher->forward(array(
"controller" => "comments",
"action" => "index"
));
}
$comment = new Comments();
$comment->model = $this->request->getPost("model");
$comment->model_id = $this->request->getPost("model_id");
$comment->body = $this->request->getPost("body");
if (!$comment->save()) {
foreach ($comment->getMessages() as $message) {
$this->flash->error($message);
}
} else {
$this->flash->success("comment was created successfully");
}
$referer = $this->request->getHTTPReferer();
$path = parse_url($referer, PHP_URL_PATH);
$this->response->redirect($path, true);
}
これで記事にコメントできるようになりました。
課題としてはCommentsControllerにControllerBaseを継承させていますが、名前空間を使用している場合はそれに依存してしまいます。
あと、ルーティングを書くのがめんどくさいです‥
※ ソースはGithubに置いています。