5547-CakePHP-tutorial-no-5-from-IBM.pdf

(228 KB) Pobierz
Cook up Web sites fast with CakePHP, Part 5: Adding cache
Cook up Web sites fast with CakePHP, Part 5: Adding cache
03/06/2007 08:19 PM
Cook up Web sites fast with CakePHP, Part 5:
Adding cache
A good way to improve the performance of your apps
Level: Intermediate
Duane O'Brien ( d@duaneobrien.com ), PHP developer, Freelance
16 Jan 2007
CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP.
This " Cook up Web sites fast with CakePHP " series shows how to build an online product
catalog using CakePHP. Part 1 focuses on getting CakePHP up and running, and Part 2
demonstrates how to use Scaffolding and Bake. Part 3 shows how to use CakePHP's Sanitize and
Security components to help secure your user-submitted data, and Part 4 focuses on the Session
component of CakePHP. Here in Part 5, you will learn how to use CakePHP's Sanitize and
Security components to help secure your user-submitted data, and you will learn how to handle
invalid requests.
Introduction
This series is designed for PHP application developers who want to start using CakePHP to make their lives
easier. In the end, you will have learned how to install and configure CakePHP, the basics of Model-View-
Controller (MVC) design, how to validate user data in CakePHP, how to use CakePHP Helpers, and how to
get an application up and running quickly using CakePHP. It might sound like a lot to learn, but don't worry --
CakePHP does most of it for you.
This article assumes you have already completed Part 1 , Part 2 , Part 3 , Part 4 , and that you still have the
working environment you set up for those pieces. If you do not have CakePHP installed, you should run
through Parts 1 and 2 before continuing.
It is assumed that you are familiar with the PHP programming language, have a fundamental grasp of database
design, and are comfortable getting your hands dirty.
System requirements
Before you begin, you need to have an environment in which you can work. CakePHP has minimal server
requirements:
1 An HTTP server that supports sessions (and preferably mod_rewrite). This article was written using
Apache V1.3 with mod_rewrite enabled.
2 PHP V4.3.2 or greater (including PHP V5). This article was written using PHP V5.0.4.
.
3 A supported database engine. Today, this means MySQL, PostgreSQL, or use of a wrapper around
ADODB. This article was written using MySQL V4.1.15.
You'll also need a database and database user ready for your application to use. This article provides the
syntax for creating any necessary tables in MySQL.
The simplest way to download CakePHP is to visit CakeForge.org and download the latest stable version. This
tutorial was written using V1.1.8. (Nightly builds and copies straight from Subversion are also available.
Details are in the CakePHP Manual (see Resources ).)
http://www-128.ibm.com/developerworks/opensource/library/os-php-cake5/
Page 1 of 11
.
.
332049150.008.png 332049150.009.png
Cook up Web sites fast with CakePHP, Part 5: Adding cache
03/06/2007 08:19 PM
Tor so far
In Part 4 , you were given an opportunity to streamline Tor . How did you do?
Adding the Favorites Action and View
To view the Favorites list, you need to add a favorites action to the users controller. It might look something
like Listing 1.
Listing 1. Adding a favorites action to the users controller
function favorites () {
$username = $this->Session->read('user');
$favorites = array();
if ($username)
{
$this->User->recursive = 2;
$results = $this->User->findByUsername($username);
foreach($results['Product'] as $product)
{
$favorites[] = array('Product' => $product, 'Dealer' => $product['Dealer']);
}
$this->set('products', $favorites);
} else {
$this->redirect('/users/login');
}
}
Note the redirection if the user is not logged in. This keeps the user from seeing an error when viewing the
page without logging in.
You would also need a favorites.html in the app/views/users/ directory. It might look something like this:
Listing 2. Favorites.html
<h2>Your Favorite Products</h2>
<?php
echo $this->renderElement('products_table', array('products' => $products) );
?>
All the view really needs to do is show the products table. However, right now, the products all show up with
an Add To Favorites link, which is silly, considering you are looking at your list of favorites. It should say
Remove From Favorites .
Putting in the Remove From Favorites Link
Your other task was to put in a Remove From Favorites link in the products table, setting it up so that users
saw the Remove link if a product was in their favorites list, and an Add link if the product was not in their
favorites list. Taking a look at the products table again, the following section is the most important.
http://www-128.ibm.com/developerworks/opensource/library/os-php-cake5/
Page 2 of 11
332049150.010.png 332049150.011.png 332049150.001.png
Cook up Web sites fast with CakePHP, Part 5: Adding cache
03/06/2007 08:19 PM
Listing 3. Products table
<?php
if ( isset($ajax) ) {
echo $ajax->link('Add to Favorites', '/products/add_to_favorites/' .
$product['Product']['id'], array('update'=>'updated', 'loading' =>
"Element.show('loading')",'complete' => "Element.hide('loading')"));
}
?>
The Remove From Favorites link will be much the same, as shown below.
Listing 4. Remove from Favorites link
echo $ajax->link('Remove from Favorites', '/products/remove_from_favorites/' .
$product['Product']['id'], array('update'=>'updated', 'loading' =>
"Element.show('loading')",'complete' => "Element.hide('loading')"));
You will also need the removeFromFavorites action in the products controller.
Listing 5. The removeFromFavorites action
function removeFromFavorites($id) {
$username = $this->Session->read('user');
$success = false;
$user = $this->Product->User->findByUsername($username, 'User.id');
$this->Product->User->id = $user['User']['id'];
$success = $this->Product->User->removeFavorite($id);
if ( $this->RequestHandler->isAjax() ) {
$this->set('products', $this->Product->findAll());
} else {
if ( $success ) {
$this->Session->setFlash('Removed product from favorites');
$this->redirect('/users/favorites');
} else {
$this->Session->setFlash('Access denied');
$this->redirect('/products/index');
}
}
}
And likewise, the removeFavorite method in the users controller must be created.
Listing 6. Creating the removeFavorite method
function removeFavorite($product_id) {
if($this->getID()) {
$user = $this->read();
$fav = array();
foreach($user['Product'] as $product) {
if ($product_id != $product['id'])
{
$fav[] = $product['id'];
}
}
$user['Product'] = array('Product'=> $fav);
if($this->save($user)) {
return true;
http://www-128.ibm.com/developerworks/opensource/library/os-php-cake5/
Page 3 of 11
332049150.002.png 332049150.003.png 332049150.004.png
Cook up Web sites fast with CakePHP, Part 5: Adding cache
03/06/2007 08:19 PM
} else {
return false;
}
}
return false;
}
As you noticed, when you view the favorites list, Add to Favorites is displayed. Instead, the user should see
the Remove from Favorites button for products they already have added to their favorites list. How would
you do that?
Caching
Conceptually, caching can sometimes be confusing. There are many types of caching, and each presents its
own set of challenges and benefits. It is important to understand in this context what is meant by caching.
What does caching mean?
Generally, caching happens anytime a request is made, and the responding application says, "I don't have to
go get that. I've already got one." Most of the time, when a computer user hears the word "cache," he thinks of
a browser's cache. Typically, in order to speed up the user experience, your browser will keep copies of what
it believes are static files -- generally images, stylesheets, static HTML, and script files. While this type of
caching can sometimes cause problems for developers of Web applications, this type of caching is not our
focus here.
Another example of caching would be when the browser makes a request of your Web application for some
content. If your Web application uses caching, it could respond to the request with a previously generated
copy of the content, eliminating the resource overhead involved in generating the content a second time. This
is the type of caching this article will focus on.
Cache why?
Generally, you would use caching in your application for two reasons. One, it helps reduce resource
consumption on your server. While the savings may be small in most cases, for high-traffic sites serving
requests in significant volume, these small savings quickly add up to significant performance benefits. The
second reason is typically speed. Because your application doesn't have to go through the process of
regenerating the content for the request, the content can be served much more quickly. Again, while the
savings may be small in most cases, high-traffic sites can quickly realize speed benefits by using caching.
Cache how?
OK -- you're sold. You are ready to cache anything and everything. How do you do it? What does CakePHP
give you to make it easy?
For starters, you need to turn caching on. By default, it's disabled. You can enable it in app/config/core.php --
look for the following entry: define('CACHE_CHECK', false); and change it to
define('CACHE_CHECK', true); .
By setting this value to true you are telling CakePHP that caching is now in play. Go ahead and do that now,
so you can set up caching later. You're not done yet: you have to tell CakePHP exactly what you want cached,
and for how long.
http://www-128.ibm.com/developerworks/opensource/library/os-php-cake5/
Page 4 of 11
332049150.005.png
Cook up Web sites fast with CakePHP, Part 5: Adding cache
03/06/2007 08:19 PM
Cache what?
Having turned caching on, you have to specify what you want cached. This starts in the controller for the
views you want to cache by adding cache to the helpers array. For example, if you want to cache the
products views, you would have to have cache in the helpers array for the products controller. When you
built the products controller for Tor, you specified that the HTML and form helpers were in use. Adding cache
to this list, the helpers array would look like this: var $helpers = array('Html',
'Form', 'Cache' ); .
Now that the cache helper is in use, you need to specify exactly what you want cached. There are several
ways you can do this, but all of them hinge on the $cacheAction array.
Cache a specific request
Suppose you wanted to cache a specific request. Suppose there are three or four products that get high traffic
on the view action, and you want to cache just the "view" views for these products. In this case, you would
specify the requests you want to cache as array keys for $cacheAction and specify the length of time as
the value for the key. The $cacheAction array is a class variable, like the $helpers array. To cache
these specific views, $cacheAction might look like Listing 7.
Listing 7. $cacheAction
var $cacheAction = array (
'view/1/' => 3600,
'view/2/' => 3600,
'view/3/' => 3600
);
This $cacheAction is telling CakePHP to cache the "view" views for products 1-3 for 3,600 seconds
(one hour). The length of time you specify can be any format that strtotime() can interpret. You could
just as easily say 1 hour .
Cache a whole action
Maybe it's not enough to just cache a few products. Perhaps you want to cache all the views for a particular
action. Suppose you want to use caching on the views for the edit action. To do so, you would specify the
action as an array key and the length of time to keep the views in cache much like you did above.
var $cacheAction = array (
'edit/' => '+1 hour'
);
You can even mix and match the two.
Listing 8. Mixing and matching
var $cacheAction = array (
'view/1/' => 3600,
'view/2/' => 3600,
'view/3/' => 3600,
'edit/' => '+1 hour'
);
That helps save some time. Now you have cached the "view" views for the most commonly viewed products
and all of the edit views. But maybe you want to do more.
http://www-128.ibm.com/developerworks/opensource/library/os-php-cake5/
Page 5 of 11
332049150.006.png 332049150.007.png
Zgłoś jeśli naruszono regulamin