Full CakePHP 1.2 App Part 11

Wow, just looked back at my last post date and realised its been a while. Anyway here's the latest post on creating a full application in CakePHP. Last time I finished off the header and this time I'm going to finish the footer. Check out the online version of the app cos I've been busy adding Dvds and its looking good.

From the view file I'm going to use the $this->requestAction() method to get data from the Dvd Controller. The requestAction() method is used to call a Controller's action from anywhere and can be extremely useful in our view files for requesting specific chunks of data.

Creating the Controller Actions

In the Dvds Controller I'm going to create 2 new methods, footer() will take care of the "top rated", "recently added", and "most active" lists. The second method top_genres() will process the Genres.

I had a quick look in the bakery and came across this article on creating Reusable Elements. Using version 1.2 I can use the paginate() method to get Dvds from the database and also pass parameters which will automatically sort our results.

This is a fantastic feature of version 1.2 and will cut down on some code. The top_genres() method is a little more involved and requires grabbing all the Genres from the database along with related Dvds. I then loop through the genres and count how many Dvds each Genre contains, I then sort the Genres into descending order and finally return the top 5 Genres with the slug as an index and the number of Dvds as the value. The code for that is included below.

In both methods below I first check that $this->params['requested'] is true. This makes sure that the requestAction method was used to get the data and redirects users to the index if they came through a URL e.g. /dvdcatalog/dvds/footer

// file: /app/controllers/dvds_controller.php

/**
 * footer()
 * gets dvds from db with passed url options
 */
function footer() {
	// if the data has been requested
	if(isset($this->params['requested'])) {
		// only get from dvd table, no joins
		$this->Dvd->recursive = -1;
		// return the dvds
		return $this->paginate();
	} else {
		// redirect to index if called directly from url
		$this->redirect(array('action'=>'index'));
	}
}

/**
 * top_genres()
 * gets the most active genres from the db
 */
function top_genres() {
	// if the data has been requested
	if(isset($this->params['requested'])) {
		// get all genres
		$genres = $this->Dvd->Genre->find('all');
		// init
		$sorted = array();
		// loop through
		foreach($genres as $key=>$g) {
			$sorted[$g['Genre']['slug']] = count($g['Dvd']);
		}
		// sort the array
		arsort($sorted);

		return array_slice($sorted, 0, 5);
	} else {
		// redirect to index
		$this->redirect(array('action'=>'index'));
	}
}

Requesting the data

From the footer view file I can use the $this->requestAction() method to run any controller action and because we're using paginate() to retrieve data from the database we can pass parameters to sort and limit the data.

In the Top Rated list for example I'm getting all the Dvds from the database, sorting them by the rating field, supplying the order in which to order them which is descending and limiting the returned result to 5 dvds. All this is done using the url being passed. How good is that!

// file: /app/views/elements/index_footer.ctp

<h2>Top Rated</h2>
<ol>
<?php
// get top rated dvds
// i'm using the paginator so i can specifiy sql statements here
$top_rated = $this->requestAction('dvds/footer/sort:rating/direction:desc/limit:5');
// loop through dvds
foreach($top_rated as $dvd) {
	echo "<li><a href='/dvds/view/".$dvd['Dvd']['slug']."'>".$dvd['Dvd']['name']."</a></li>";
}
?>
</ol>

Further reading on paginate() can be viewed here, here and here

Most Active Dvds

I was running out of lists to display so I created a "most active" list that requires some minor changes to the database. Each time a DVD is viewed I'm going to increment a "view" count so that I can order Dvds by the number of times they have been viewed. Here's the SQL for this change:

ALTER TABLE `dvds` ADD `views` INT NOT NULL AFTER `episodes` ;

A minor change is also required in the view() action of the Dvds Controller. I'm simply going to save the incremented value of the "views" field and this is done every time a Dvd is viewed.

// if dvd has been found
if(!empty($dvd)) {
	// save genres string
	$dvd['Dvd']['genres'] = $this->_create_genre_string($dvd['Genre']);
	// set the dvd for the view
	$this->set('dvd', $dvd);

	// increment the number of items the dvd was viewed
	$this->Dvd->save(array(
		'Dvd' => array(
			'id' => $dvd['Dvd']['id'],
			'views' => ($dvd['Dvd']['views'] + 1)
		)
	));
}

Create a Reusable Element

Although the way I've done things is all fine and well, we can improve things some more by creating reusuable elements incase I want to use these lists in other places. The first to do in create 4 new files in the /app/views/elements folder, a file for each of the lists.

Once the code has been extracted to the 4 different files I can include them by calling the $this->element() method, now whenever I want to display these lists I can simply call the method with the name of the file like below.

// file: /app/views/elements/index_footer.ctp

<h2>Top Rated</h2>
<?php echo $this->element('top_rated');?>
// file: /app/views/elements/top_rated.ctp

<ol>
<?php
// get top rated dvds
// i'm using the paginator so i can specifiy sql statements here
$top_rated = $this->requestAction('dvds/footer/sort:rating/direction:desc/limit:5');
// loop through dvds
foreach($top_rated as $dvd) {
	echo "<li><a href='/dvds/view/".$dvd['Dvd']['slug']."'>".$dvd['Dvd']['name']."</a></li>";
}
?>
</ol>

Improving Performance

Given that there are quite a few SQL queries being performed on the database we can improve performance by caching the results by a set time period. This is really easy todo by supplying a time period when including the element like this:

// file: /app/views/elements/index_footer.ctp

<h2>Recently Added</h2>
<?php echo $this->element('recently_added', array('cache'=>'+1 hour'));?> 

Just a quick note make sure your /app/tmp folder is writable with the correct permissions as your file wont be cached.

Wrapping Up

Ok so I've finally got round to completing the front page of the application. I've covered the paginate() method and the process of creating a reusable element that is avaliable througout the application. I've also covered using the requestAction() method for retrieving data from a controller action whilst in a view.

Source Code

The source code for this article can be downloaded using this link. If these articles are helping you out why not consider donating I can always use a beer! :)

Next Article

Whilst testing the application online and adding Dvds I noticed a few bugs and display errors that need to be addressed so those things are on my todo list. As with any large application these types of things occur and hopefully they wont be difficult to fix.

Posted on 3rd August 2008
8 years, 9 months, 3 weeks, 1 day ago

comments powered by Disqus