Codeigniter, one of the fabulous PHP frameworks now available to give you a jumpstart on your PHP custom code projects, has, as of version 1.7, a really handy cart class. I was able to get a cart system up and running without writing a lot of custom code and concentrate on only the custom needs of the client’s particular business model.
Out of the box, the cart class would not accept some of my products into the cart, silently refusing to add them to the cookie. It was any project with a comma or quotes in the product name. Looking at the base CodeIgniter cart class, line 30(ish), you will find:
[php]
var $product_name_rules = ‘\.\:\-_ a-z0-9’; // alpha-numeric, dashes, underscores, colons or periods
[/php]
and this variable is used in the _insert() function around line 186:
[php]
if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items[‘id’]))
{
log_message(‘error’, ‘Invalid product ID. The product ID can only contain alpha-numeric characters, dashes, and underscores’);
return FALSE;
}
[/php]
So, the upshot is that it doesn’t silently ignore your request, it’s logging the error, but not to screen (or to your future customers). The CodeIgniter forum users suggest that developers change the regular expression held in $product_name_rules to something that matches their needs, including some suggestions to set it just to ‘.’ (matching everything) directly in the libraries/cart.php Cart Class and call it done. This is not the right way. If you are anything like me, you’ll upgrade CodeIgniter to the latest and greatest in the next year, long after you forgot your core file change, and the client will loose sales on some of the products that contain strange characters. The real solution is to extend the Cart class by putting your change in your application/libraries/MY_Cart.php file. This change simply extends the cart class and lets you specify a new regular expression to match your online store’s product naming needs.
Here’s my new MY_Cart.php file, extending $product_name_rules to include commas, parenthesis and quotes in product names. Adjust recipe, bake and serve according to taste:
[php]
<?php
class MY_Cart extends CI_Cart {
function __construct() {
parent::CI_Cart();
$this->product_name_rules = ‘\,\(\)\"\’\.\:\-_ a-z0-9’;
}
}
[/php]