summaryrefslogtreecommitdiff
path: root/demos/blog-tutorial/samples/day5/blog/protected/pages/posts/ReadPost.php
blob: aac5cac7e0914d9cb35b9b0a14130444d9b2a314 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php

Prado::using('Application.BlogException');

class ReadPost extends TPage
{
	private $_post;
	/**
	 * Fetches the post data.
	 * This method is invoked by the framework when initializing the page
	 * @param mixed event parameter
	 */
	public function onInit($param)
	{
		parent::onInit($param);
		// post id is passed via the 'id' GET parameter
		$postID=(int)$this->Request['id'];
		// retrieves PostRecord with author information filled in
		$this->_post=PostRecord::finder()->withAuthor()->findByPk($postID);
		if($this->_post===null)  // if post id is invalid
			throw new BlogException(500,'Unable to find the specified post.');
		// set the page title as the post title
		$this->Title=$this->_post->title;
	}

	/**
	 * @return PostRecord the PostRecord currently being viewed
	 */
	public function getPost()
	{
		return $this->_post;
	}

	/**
	 * Deletes the post currently being viewed
	 * This method is invoked when the user clicks on the "Delete" button
	 */
	public function deletePost($sender,$param)
	{
		// only the author or the administrator can delete a post
		if(!$this->canEdit())
			throw new THttpException('You are not allowed to perform this action.');
		// delete it from DB
		$this->_post->delete();
		// redirect the browser to the homepage
		$this->Response->redirect($this->Service->DefaultPageUrl);
	}

	/**
	 * @return boolean whether the current user can edit/delete the post being viewed
	 */
	public function canEdit()
	{
		// only the author or the administrator can edit/delete a post
		return $this->User->Name===$this->Post->author_id || $this->User->IsAdmin;
	}
}