<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MasterJrock.com</title>
	<atom:link href="http://www.masterjrock.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.masterjrock.com</link>
	<description>Jack of all trades, master of none.</description>
	<lastBuildDate>Wed, 04 Aug 2010 12:48:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Dynamic Upsell using Ext-js via JSON</title>
		<link>http://www.masterjrock.com/dynamic-upsell-using-ext-js-via-json.html</link>
		<comments>http://www.masterjrock.com/dynamic-upsell-using-ext-js-via-json.html#comments</comments>
		<pubDate>Wed, 04 Aug 2010 05:05:58 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[Ext-js]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[DataView]]></category>
		<category><![CDATA[ext-js]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[magento]]></category>
		<category><![CDATA[upsell products]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=17</guid>
		<description><![CDATA[One of the best ways to increase sales is to sell to your existing customers – or those who already want to buy from you – by increasing their average spend. In this post, I've created a dynamic way to upsell related items by the current product category using Ext-js DataView. The data of course was loaded via JSON to increase load page performance.]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">O</span>ne of the best ways to increase sales is to sell to your existing customers – or those who already want to buy from you – by increasing their average spend. The beauty of cross-selling and up-selling is that you are selling to   people who are already interested in buying from you by letting them   know what else you can do for them, so your job is made much easier than   if you were selling to a cold lead. The key is to sell them something   that is <em>relevant</em> and <em>useful</em>. </p>
<p>In this post, I&#8217;ve created a dynamic way to upsell related items by the current product category using Ext-js DataView. The data of course was loaded via JSON to increase load page performance.</p>
<p>Modifying the upsell.phtml, I came up with this:</p>
<pre class="brush:php">
global $attribute_code, $attributeSets;

$attribute_code = array(
    array('code'=>'sku','label'=>'Link / SKU','sortable' =>'true','width' =>125,'type'=>'text'),
    array('code'=>'special_price','label'=>'Special Price','sortable' =>'true','width' =>100,'type'=>'float'),
    array('code'=>'addtocart','type'=>'text'),
    array('code'=>'short_description', 'type'=>'text'),
    array('code'=>'url_path', 'type'=>'text'),
    array('code'=>'image', 'type'=>'text'),
    array('code'=>'name', 'type'=>'text'),
    array('code'=>'order', 'type'=>'int'),
    array('code'=>'productId', 'type'=>'int')
);

//Fields
if (!function_exists('_setExtField')) {
    function _setExtField() {
        global $attribute_code;
        $field_array = array();
        foreach ( $attribute_code as $item =>$value ) {
            $field_array[] = "{name: '".$value['code']."', type: '".$value['type']."'}";
        }
        return implode(',', $field_array);
    }
}

$pageSize = 25; //default page size

//Get Current Product
$_product = $this->getProduct();
$current_product_catIds = $_product->getCategoryIds();
</pre>
<p>Since my product category setup ids were setup as array([parent],[child]) and the second index is alwasy present, I will take note only the second index value</p>
<pre class="brush:php">
$ids = $current_product_catIds[1];
</pre>
<p>Then our basic Ext-js requirements:</p>
<pre class="brush:xml">
<style type="text/css">@import url("/js/ext/resources/css/ext-all.css");</style>
<style type="text/css">@import url("<?= $this->getSkinUrl()?>css/your_dataview_styling.css");</style>

<script type="text/javascript" src="/js/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/js/ext/ext-all.js"></script>
</pre>
<p>Then our Ext.DataView call</p>
<pre class="brush:javascript">
Ext.onReady(function(){
	//Defaults
	var fields = [<?= _setExtField()?>];
	var emptyText = '
<div style="padding:10px;">No items match the specified filter</div>

';
	var loadingText = 'Loading data...Please wait.';
	var itemSelector = 'div.thumb-wrap';
	var overClass = 'x-view-over';
	var listTemplate = new Ext.XTemplate('
<div>','<tpl for=".">','
<div id="_items-{id}">','
<div class="thumb-wrap" id="{name}">','
<div class="thumb"><a href="{url_path}"><img src="{image}" title="{name}"></a></div>

','
<h5><a href="{url_path}" title="{sku}">{name}</a></h5>

','
<div class="price-box">
<p class="special-price"><span class="price-label">Special Price:</span><span class="price" id="product-price-{productId}">{special_price:usMoney}</span>
</div>

','<a href="{addtocart}"><button class="form-button"><span>Add to Cart</span></button></a>','</div>

','</div>

','</tpl>','</div>

');
	var width = 686;
	var height = 305;
	var checkImage = function(data){if(data.image == 'no_selection' || data.image == null) {return '[your_image_place_holder_path_and_file]';} else {return '[your_cache_thumbnail_path]'+ data.image;}}
	var formatData = function(data){data.image = checkImage(data); return data;};

	//Loop
	var proxy__<?= $ids ?> = new Ext.data.HttpProxy({ url: '/remote-data.php?cat=<?= $ids ?>', method: 'POST', prettyUrls: false});
	var store__<?= $ids ?> = new Ext.data.JsonStore({proxy : proxy__<?= $ids ?>, root: 'items',totalProperty: 'totalcount',idProperty: 'sku',remoteSort: true,fields: fields});
	store__<?= $ids ?>.load({params:{start:0, limit:<?= $pageSize?>}});
	var bbar__<?= $ids ?> = new Ext.PagingToolbar({ store: store__<?= $ids ?>, pageSize: <?= $pageSize ?>, displayInfo: true, displayMsg: 'Displaying items {0} - {1} of {2}', emptyMsg: 'No items to display'});
	var view__<?= $ids ?> = new Ext.DataView({ store: store__<?= $ids ?>, tpl: listTemplate, loadingText: loadingText,overClass: overClass, itemSelector: itemSelector, emptyText : emptyText,
		prepareData: formatData.createDelegate()
	});

	var panel__<?= $ids ?> = new Ext.Panel({
    	id: 'item-chooser-dlg',autoScroll: true,width : width, height : height, collapsible : true,
		title : '<?= $this->__('You may also be interested in other our ') . Mage::getModel('catalog/category')->load($ids)->getName(); ?>',
		items: [{ id: 'item-chooser-view', autoScroll: true, items: view__<?= $ids ?>, }],
		renderTo : 'dataView_<?= $ids ?>',
		bbar: bbar__<?= $ids ?>
	});
	panel__<?= $ids ?>.show();
});
</pre>
<p>Source:<br />
<a href="http://www.masterjrock.com/wp-content/demos/ext-js/remote-data.txt" title="Remote Data - Response" target="_blank">Remote JSON Data – Response</a><br />
<a href="http://www.masterjrock.com/wp-content/demos/ext-js/remote-data.php.txt" title="Magento Remote Data Script" target="_blank">remote-data.php</a><br />
<a href="http://www.masterjrock.com/wp-content/demos/ext-js/upsell.phtml.txt" title="Upsell.phtml in Magento" target="_blank">Upsell.phtml</a></p>
<p><a href="http://www.shivumjewelryoutlet.com/97222.html" title="Dynamic Way to Upsell Products using Ext-JS in Magento" target="_blank">See working example here</a>.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/dynamic-upsell-using-ext-js-via-json.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Categorize Related Products in Magento</title>
		<link>http://www.masterjrock.com/categorize-related-products-in-magento.html</link>
		<comments>http://www.masterjrock.com/categorize-related-products-in-magento.html#comments</comments>
		<pubDate>Tue, 03 Aug 2010 10:41:32 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[categorize]]></category>
		<category><![CDATA[magento]]></category>
		<category><![CDATA[related products]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=13</guid>
		<description><![CDATA[Would it be easier when you but stuff at a particular website that shows you all of the related products you might want to add in your shopping cart. Take for instance buying a inkjet printer and you might want to buy of course additional cartridges that comes with it.]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">W</span>ould it be easier when you but stuff at a particular website that shows you all of the related products you might want to add in your shopping cart. Take for instance buying a inkjet printer and you might want to buy of course additional cartridges that comes with it.</p>
<p>In this post, the <em><strong>setOrder</strong></em> function comes into place</p>
<p>Copy <em><strong>Crosssell.php</strong></em> into <em><strong>app/code/local/Mage/Checkout/Block/Cart</strong></em></p>
<p>Then, at line 150: <em><strong>_getCollection()</strong></em> function, insert <em><strong>setOrder</strong></em> function and set the attribute code and order parameter you desire. </p>
<pre class="brush:php">
protected function _getCollection() {
    $collection = Mage::getModel('catalog/product_link')->useCrossSellLinks()
        ->getProductCollection()
        ->setStoreId(Mage::app()->getStore()->getId())
        ->addStoreFilter()
        ->setOrder('attribute_set_id', 'asc') // Order by attribute set
        ->setPageSize($this->_maxItemCount);
    $this->_addProductAttributesAndPrices($collection);

    Mage::getSingleton('catalog/product_status')
    	->addSaleableFilterToCollection($collection);
    Mage::getSingleton('catalog/product_visibility')
    	->addVisibleInCatalogFilterToCollection($collection);
    Mage::getSingleton('cataloginventory/stock')
    	->addInStockFilterToCollection($collection);

    return $collection;
}
</pre>
<p>This also applies if you&#8217;re going to use the Related.php, instead of Crosssell.php.In my case, I&#8217;m stuck and okay with using the latter.</p>
<p>And my template would be this:</p>
<pre class="brush:php">
foreach($this->getItems() as $_item): ?>
    if ( $setId != $_item->getAttributeSetId() ) :
        $setId = $_item->getAttributeSetId();
</pre>
<pre class="brush:xml">
<li class="attributeSetId"><?= _getAttributeSet( $_item->getAttributeSetId() ) ?></li>
</pre>
<p>Now, I cant&#8217; figure out how to get the attribute set name by id, so <em><strong>product_attribute_set.list</strong></em> SoapCleint service method. Hope someone will shed some light.</p>
<pre class="brush:php">
global $attribute_code, $attributeSets;

$proxy = new SoapClient($this->getBaseUrl().'api/soap/?wsdl');
$sessionId = $proxy->login('your apiUser', 'your apiKey');
$attributeSets = $proxy->call($sessionId, 'product_attribute_set.list');

//Get Attrinute Name
if (!function_exists('_getAttributeSet')) {
    function _getAttributeSet($id) {
        global $attributeSets;
        $setName = '';
        foreach($attributeSets as $set) {
            if ($set['set_id'] == $id ) {
                $setName = $set['name'];
            }
        }
        return $setName;
    }
}
</pre>
<p>That&#8217;s it. Enjoy!</p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/categorize-related-products-in-magento.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Advanced Ext-Js Grid with JSON Data and Cell Actions</title>
		<link>http://www.masterjrock.com/advanced-ext-js-grid-with-json-data-and-cell-actions.html</link>
		<comments>http://www.masterjrock.com/advanced-ext-js-grid-with-json-data-and-cell-actions.html#comments</comments>
		<pubDate>Mon, 02 Aug 2010 09:22:24 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[Ext-js]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Cell Actions]]></category>
		<category><![CDATA[ext-js]]></category>
		<category><![CDATA[ext-js plugin]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[Grid.Panel]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[magento]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=11</guid>
		<description><![CDATA[<p>In my basic grid example, Data was loaded within the javascript call. This post contains an advanced demonstration of using AJAX/JSON to load data remotely for better performance. You will notice that the web page rendered quickly and proceeds before loading the data remotely.</p>]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">I</span>n my basic grid example, Data was loaded within the javascript call. This post contains an advanced demonstration of using AJAX/JSON to load data remotely for better performance. You will notice that the web page rendered quickly and proceeds before loading the data remotely.</p>
<p>To make use of the fields and columns more efficiently and accurately. I&#8217;ve used PHP arrays to construct them as I want to.</p>
<pre class="brush:php">
global $attribute_code;
$attribute_code = array(
    array('code'=>'sku','label'=>'Item','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_diamond_color','label'=>'DiamondColor','sortable' =>'true','width' =>50,'type'=>'text'),
    array('code'=>'jewelry_diamond_clarity','label'=>'DiamondClarity','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_gemstone_color','label'=>'GemstoneColor','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_gemstone_clarity','label'=>'GemstoneClarity','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_carat_total_weight','label'=>'CaratWeight','sortable' =>'true','width' =>50,'type'=>'float'),
    array('code'=>'jewelry_main_stone','label'=>'MainStone','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_metal_purity','label'=>'MetalPurity','sortable' =>'true','width' =>50,'type'=>'text'),
    array('code'=>'jewelry_style','label'=>'Style','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_metal','label'=>'Metal','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'special_price','label'=>'SpecialPrice','sortable' =>'true','width' =>100,'type'=>'float'),
    array('code'=>'addtocart','type'=>'text'),
    array('code'=>'short_description', 'type'=>'text'),
    array('code'=>'url_path', 'type'=>'text'),
    array('code'=>'image', 'type'=>'text'),
    array('code'=>'name', 'type'=>'text')
);
</pre>
<p>Then I created a function to make fields/columns javascript arrays suitable for my <em><strong>Ext.data.JsonStore</strong></em> requirements</p>
<pre class="brush:php">
  //Fields
  if (!function_exists('_setExtField')) {
      function _setExtField() {
          global $attribute_code;
          $field_array = array();
          foreach ( $attribute_code as $item =>$value ) {
              $field_array[] = "{name: '".$value['code']."', type: '".$value['type']."'}";
          }
          return implode(',', $field_array);
      }
  }

  //Column
  if (!function_exists('_setExtColumn')) {
      function _setExtColumn() {
          global $attribute_code;
          $column_array = array();
          foreach ( $attribute_code as $item => $value ) {
              if ( isset($value['label']) &#038;&#038;  $value['label'] != NULL) {
                  $column_label = $value['label'];
                  $column_code = $value['code'];
                  $column_sortable = $value['sortable'];

                  if ($column_code == 'sku')
                      $column_array[]  = "{id:'$column_code',header: '$column_label', sortable: $column_sortable, renderer: renderUrl, dataIndex: '$column_code'}";
                  elseif ($column_code == 'special_price')
                      $column_array[]  = "{header: '$column_label', sortable: $column_sortable, renderer: 'usMoney', dataIndex: '$column_code', cellActions:[{iconCls:'x-btn-cart',qtip:'Add this to cart', style: 'background: transparent url(/wp-includes/js/ext/shared/icons/fam/shop_cart.png) no-repeat;'}]}";
                  else {
                      $column_array[]  = "{header: '$column_label', sortable: $column_sortable, dataIndex: '$column_code'}";
                  }
              }
          }
          return implode(',', $column_array);
      }
  }
</pre>
<p>To make use of a simple html data formatting for each of my data whenever it loads into my grid, I make use of a <em><strong>renderer</strong></em> option</p>
<p>. The <em><strong>renderer</strong></em> option calls a specified javascript function <em><strong>renderUrl</strong></em> and <em><strong>usMoney</strong></em>. <em><strong>usMoney</strong></em> is already built in into Ext-Js library.</p>
<p>Now my Ext.data.JsonStore looks like this:</p>
<pre class="brush:javascript">
    var store = new Ext.data.JsonStore({
        root: 'items', //root tag for all of my items
        totalProperty: 'totalcount', // total count tag for my items
        idProperty: 'sku',
        remoteSort: true, //sort remotely from data
        fields: [<?= _setExtField();?>],
        proxy: new Ext.data.ScriptTagProxy({
			url: '[your_remote_url'
        })
    });
</pre>
<p>Take note <em><strong>root</strong></em> &amp; <em><strong>totalProperty</strong></em> properties. This should be visible in your JSON data. Verifying you JSON data makes it easy at <a rel="nofollow" href="http://www.jsonlint.com/" target="_blank">JSON Validator website</a>.</p>
<p>At the <em><strong>proxy</strong></em> property, I make use of <em><strong>Ext.data.ScriptTagProxy</strong></em> class. Using this javascript class requires an extra JSON entry "callback" in your response data. If your remote data script sits in on the same server, using <em><strong>Ext.data.HttpProxy</strong></em> is recommended.</p>
<pre class="brush:javascript">
proxy : new Ext.data.HttpProxy({
    method: 'POST',
    prettyUrls: false,
    url: '/remote-data.php?cat=7'
})
</pre>
<p>You probably want to konw how I did my my "<strong>remote-data.php</strong>". My remote data sits on a Magento driven web site. As I mention above, "<em><strong>Ext.data.ScriptTagProxy</strong></em>" uses an exra "<em><strong>callback</strong></em>" response. Therefore your php script should have something like this if you want your remote data script usable across domains.</p>
<pre class="brush:php">
$categoryId 	= intval(@$_GET['cat']);
$limit 			= ( isset($_POST['limit']) )?  intval(@$_POST['limit']) : intval(@$_GET['limit']) ;
$start 			= ( isset($_POST['start']) )?  intval(@$_POST['start']) : intval(@$_GET['start']) ;
$direction 		= ( isset($_POST['dir']) )?  @$_POST['dir'] : @$_GET['dir'] ;
$sort 			= ( isset($_POST['sort']) )?  @$_POST['sort'] : @$_GET['sort'] ;

//start output
if ( isset($_REQUEST['callback']) ) {
	// if you use Ext.data.ScriptTagProxy
    $callback = $_REQUEST['callback'];
    echo $callback . '(' . json_encode(array('totalcount' => [count], 'items' => [array of items]) ) . ');';
} else {
	// if you use Ext.data.HttpProxy
    echo json_encode(array('totalcount' => [count], 'items' => [[array of items]]) );
}
</pre>
<p>Make use of an <em><strong>array_slice</strong></em> function to limit your data as <em><strong>Ext.grid.GridPanel</strong></em> request it. Then create a json data from it by using php arrays and the magical <em><strong>json_encode</strong></em> function</p>
<pre class="brush:php">
foreach( array_slice(_getProducts($categoryId, $sort, $direction),$start,$limit) as $productId) {
    $product = Mage::getModel('catalog/product');
    $product->load($productId);

    $productTitle 		= _extSanitize($product->getName());
    $productTitleTrim 	= _trimProductName($productTitle);	

    $rawData['id']							=  $ctr;
    $rawData['sku']							=  $product->getSku();
    $rawData['name']						=  $product->getName();
    $rawData['url_path']					=  $product->getProductUrl();
    $rawData['jewelry_style'] 				= _extSanitize(_getProductAttribute($product , 'jewelry_style'));
    $rawData['jewelry_carat_total_weight'] 	= floatval(_getProductAttribute($product , 'jewelry_carat_total_weight'));
    $rawData['jewelry_main_stone']	 		= _getProductAttribute($product , 'jewelry_main_stone');
    $rawData['jewelry_metal_purity'] 		= _getProductAttribute($product , 'jewelry_metal_purity');
    $rawData['jewelry_metal']			 	= _getProductAttribute($product , 'jewelry_metal');
    $rawData['jewelry_diamond_color'] 		= _getProductAttribute($product , 'jewelry_diamond_color');
    $rawData['jewelry_diamond_clarity'] 	= _getProductAttribute($product , 'jewelry_diamond_clarity');
    $rawData['jewelry_gemstone_color'] 		= _getProductAttribute($product , 'jewelry_gemstone_color');
    $rawData['jewelry_gemstone_clarity'] 	= _getProductAttribute($product , 'jewelry_gemstone_clarity');
    $rawData['special_price'] 				= floatval($product->getSpecialPrice());
    $rawData['image']						= $product->getImage();
    $rawData['addtocart'] 					= Mage::getUrl('checkout/cart/add', array('product'=>$productId));
    $rawData['short_description'] 			= $product->getShortDescription();
    $items[] = $rawData;
    $ctr++;
}
</pre>
<p>Take note of variable type you are going to declare. It should be the same as you declare it from your <em><strong>Ext.data.JsonStore</strong></em> fields property</p>
<pre class="brush:php">
    $rawData['jewelry_carat_total_weight'] 	= floatval(_getProductAttribute($product , 'jewelry_carat_total_weight'));
    $rawData['special_price'] 				= floatval($product->getSpecialPrice());
</pre>
<p>And my demo should be probably be <a href="http://www.masterjrock.com/wp-content/demos/ext-js/paging.php" title="Advanced Data Grid via JSON with Cell Actions" target="_blank">here</a>. Enjoy!</p>
<p>Source:<br />
    <a href="/wp-content/demos/ext-js/remote-data.txt" title="Remote Data - Response" target="_blank">Remote JSON Data &#8211; Response</a><br />
    <a href="/wp-content/demos/ext-js/remote-data.php.txt" title="Magento Remote Data Script" target="_blank">remote-data.php</a><br />
    <a href="http://cellactions.extjs.eu/source.php?file=js/Ext.ux.grid.CellActions.js" title="Ext.ux.grid.CellActions Plugin by Saki" target="_blank">Ext.ux.grid.CellActions.js</a>
</p>
<p>Credits:<br />
  <a href="http://cellactions.extjs.eu/" title="Ext.ux.grid.CellActions Plugin by Saki" target="_blank" rel="nofollow">Ext.ux.grid.CellActions Plugin by Saki</a><br />
  <a href="http://www.sencha.com/deploy/dev/docs/" title="ExtJS 3.2.1 API Documentation" target="_blank" rel="nofollow">ExtJS 3.2.1 API Documentation</a><br />
  <a href="http://www.sencha.com/deploy/dev/examples/grid/paging.html" title="Original Ext-JS Paging Example" target="_blank">Original Ext-JS Paging Example</a>
</p>
<p>In my basic grid example, Data was loaded within the javascript call. This post contains an advanced demonstration of using AJAX/JSON to load data remotely for better performance. You will notice that the web page rendered quickly and proceeds before loading the data remotely.</p>
<p>To make use of the fields and columns more efficiently and accurately. I&#8217;ve used PHP arrays to construct them as I want to.</p>
<pre class="brush:php">
global $attribute_code;
$attribute_code = array(
    array('code'=>'sku','label'=>'Item','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_diamond_color','label'=>'DiamondColor','sortable' =>'true','width' =>50,'type'=>'text'),
    array('code'=>'jewelry_diamond_clarity','label'=>'DiamondClarity','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_gemstone_color','label'=>'GemstoneColor','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_gemstone_clarity','label'=>'GemstoneClarity','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_carat_total_weight','label'=>'CaratWeight','sortable' =>'true','width' =>50,'type'=>'float'),
    array('code'=>'jewelry_main_stone','label'=>'MainStone','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_metal_purity','label'=>'MetalPurity','sortable' =>'true','width' =>50,'type'=>'text'),
    array('code'=>'jewelry_style','label'=>'Style','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'jewelry_metal','label'=>'Metal','sortable' =>'true','width' =>75,'type'=>'text'),
    array('code'=>'special_price','label'=>'SpecialPrice','sortable' =>'true','width' =>100,'type'=>'float'),
    array('code'=>'addtocart','type'=>'text'),
    array('code'=>'short_description', 'type'=>'text'),
    array('code'=>'url_path', 'type'=>'text'),
    array('code'=>'image', 'type'=>'text'),
    array('code'=>'name', 'type'=>'text')
);
</pre>
<p>Then I created a function to make fields/columns javascript arrays suitable for my <em><strong>Ext.data.JsonStore</strong></em> requirements</p>
<pre class="brush:php">
  //Fields
  if (!function_exists('_setExtField')) {
      function _setExtField() {
          global $attribute_code;
          $field_array = array();
          foreach ( $attribute_code as $item =>$value ) {
              $field_array[] = "{name: '".$value['code']."', type: '".$value['type']."'}";
          }
          return implode(',', $field_array);
      }
  }

  //Column
  if (!function_exists('_setExtColumn')) {
      function _setExtColumn() {
          global $attribute_code;
          $column_array = array();
          foreach ( $attribute_code as $item => $value ) {
              if ( isset($value['label']) &#038;&#038;  $value['label'] != NULL) {
                  $column_label = $value['label'];
                  $column_code = $value['code'];
                  $column_sortable = $value['sortable'];

                  if ($column_code == 'sku')
                      $column_array[]  = "{id:'$column_code',header: '$column_label', sortable: $column_sortable, renderer: renderUrl, dataIndex: '$column_code'}";
                  elseif ($column_code == 'special_price')
                      $column_array[]  = "{header: '$column_label', sortable: $column_sortable, renderer: 'usMoney', dataIndex: '$column_code', cellActions:[{iconCls:'x-btn-cart',qtip:'Add this to cart', style: 'background: transparent url(/wp-includes/js/ext/shared/icons/fam/shop_cart.png) no-repeat;'}]}";
                  else {
                      $column_array[]  = "{header: '$column_label', sortable: $column_sortable, dataIndex: '$column_code'}";
                  }
              }
          }
          return implode(',', $column_array);
      }
  }
</pre>
<p>To make use of a simple html data formatting for each of my data whenever it loads into my grid, I make use of a <em><strong>renderer</strong></em> option</p>
<p>. The <em><strong>renderer</strong></em> option calls a specified javascript function <em><strong>renderUrl</strong></em> and <em><strong>usMoney</strong></em>. <em><strong>usMoney</strong></em> is already built in into Ext-Js library.</p>
<p>Now my Ext.data.JsonStore looks like this:</p>
<pre class="brush:javascript">
    var store = new Ext.data.JsonStore({
        root: 'items', //root tag for all of my items
        totalProperty: 'totalcount', // total count tag for my items
        idProperty: 'sku',
        remoteSort: true, //sort remotely from data
        fields: [<?= _setExtField();?>],
        proxy: new Ext.data.ScriptTagProxy({
			url: '[your_remote_url'
        })
    });
</pre>
<p>Take note <em><strong>root</strong></em> &amp; <em><strong>totalProperty</strong></em> properties. This should be visible in your JSON data. Verifying you JSON data makes it easy at <a rel="nofollow" href="http://www.jsonlint.com/" target="_blank">JSON Validator website</a>.</p>
<p>At the <em><strong>proxy</strong></em> property, I make use of <em><strong>Ext.data.ScriptTagProxy</strong></em> class. Using this javascript class requires an extra JSON entry "callback" in your response data. If your remote data script sits in on the same server, using <em><strong>Ext.data.HttpProxy</strong></em> is recommended.</p>
<pre class="brush:javascript">
proxy : new Ext.data.HttpProxy({
    method: 'POST',
    prettyUrls: false,
    url: '/remote-data.php?cat=7'
})
</pre>
<p>You probably want to know how I did my my "<strong>remote-data.php</strong>". My remote data sits on a Magento driven web site. As I mention above, "<em><strong>Ext.data.ScriptTagProxy</strong></em>" uses an exra "<em><strong>callback</strong></em>" response. Therefore your php script should have something like this if you want your remote data script usable across domains.</p>
<pre class="brush:php">
$categoryId 	= intval(@$_GET['cat']);
$limit 			= ( isset($_POST['limit']) )?  intval(@$_POST['limit']) : intval(@$_GET['limit']) ;
$start 			= ( isset($_POST['start']) )?  intval(@$_POST['start']) : intval(@$_GET['start']) ;
$direction 		= ( isset($_POST['dir']) )?  @$_POST['dir'] : @$_GET['dir'] ;
$sort 			= ( isset($_POST['sort']) )?  @$_POST['sort'] : @$_GET['sort'] ;

//start output
if ( isset($_REQUEST['callback']) ) {
	// if you use Ext.data.ScriptTagProxy
    $callback = $_REQUEST['callback'];
    echo $callback . '(' . json_encode(array('totalcount' => [count], 'items' => [array of items]) ) . ');';
} else {
	// if you use Ext.data.HttpProxy
    echo json_encode(array('totalcount' => [count], 'items' => [[array of items]]) );
}
</pre>
<p>Make use of an <em><strong>array_slice</strong></em> function to limit your data as <em><strong>Ext.grid.GridPanel</strong></em> request it. Then create a json data from it by using php arrays and the magical <em><strong>json_encode</strong></em> function</p>
<pre class="brush:php">
foreach( array_slice(_getProducts($categoryId, $sort, $direction),$start,$limit) as $productId) {
    $product = Mage::getModel('catalog/product');
    $product->load($productId);

    $productTitle 		= _extSanitize($product->getName());
    $productTitleTrim 	= _trimProductName($productTitle);	

    $rawData['id']							=  $ctr;
    $rawData['sku']							=  $product->getSku();
    $rawData['name']						=  $product->getName();
    $rawData['url_path']					=  $product->getProductUrl();
    $rawData['jewelry_style'] 				= _extSanitize(_getProductAttribute($product , 'jewelry_style'));
    $rawData['jewelry_carat_total_weight'] 	= floatval(_getProductAttribute($product , 'jewelry_carat_total_weight'));
    $rawData['jewelry_main_stone']	 		= _getProductAttribute($product , 'jewelry_main_stone');
    $rawData['jewelry_metal_purity'] 		= _getProductAttribute($product , 'jewelry_metal_purity');
    $rawData['jewelry_metal']			 	= _getProductAttribute($product , 'jewelry_metal');
    $rawData['jewelry_diamond_color'] 		= _getProductAttribute($product , 'jewelry_diamond_color');
    $rawData['jewelry_diamond_clarity'] 	= _getProductAttribute($product , 'jewelry_diamond_clarity');
    $rawData['jewelry_gemstone_color'] 		= _getProductAttribute($product , 'jewelry_gemstone_color');
    $rawData['jewelry_gemstone_clarity'] 	= _getProductAttribute($product , 'jewelry_gemstone_clarity');
    $rawData['special_price'] 				= floatval($product->getSpecialPrice());
    $rawData['image']						= $product->getImage();
    $rawData['addtocart'] 					= Mage::getUrl('checkout/cart/add', array('product'=>$productId));
    $rawData['short_description'] 			= $product->getShortDescription();
    $items[] = $rawData;
    $ctr++;
}
</pre>
<p>Take note of variable type you are going to declare. It should be the same as you declare it from your <em><strong>Ext.data.JsonStore</strong></em> fields property</p>
<pre class="brush:php">
    $rawData['jewelry_carat_total_weight'] 	= floatval(_getProductAttribute($product , 'jewelry_carat_total_weight'));
    $rawData['special_price'] 				= floatval($product->getSpecialPrice());
</pre>
<p>And my demo should be probably be <a href="http://www.masterjrock.com/wp-content/demos/ext-js/paging.php" title="Advanced Data Grid via JSON with Cell Actions" target="_blank">here</a>. Enjoy!</p>
<p>Source:<br />
    <a href="/wp-content/demos/ext-js/remote-data.txt" title="Remote Data - Response" target="_blank">Remote JSON Data &#8211; Response</a><br />
    <a href="/wp-content/demos/ext-js/remote-data.php.txt" title="Magento Remote Data Script" target="_blank">remote-data.php</a><br />
    <a href="http://cellactions.extjs.eu/source.php?file=js/Ext.ux.grid.CellActions.js" title="Ext.ux.grid.CellActions Plugin by Saki" target="_blank">Ext.ux.grid.CellActions.js</a>
</p>
<p>Credits:<br />
  <a href="http://cellactions.extjs.eu/" title="Ext.ux.grid.CellActions Plugin by Saki" target="_blank" rel="nofollow">Ext.ux.grid.CellActions Plugin by Saki</a><br />
  <a href="http://www.sencha.com/deploy/dev/docs/" title="ExtJS 3.2.1 API Documentation" target="_blank" rel="nofollow">ExtJS 3.2.1 API Documentation</a><br />
  <a href="http://www.sencha.com/deploy/dev/examples/grid/paging.html" title="Original Ext-JS Paging Example" target="_blank">Original Ext-JS Paging Example</a></p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/advanced-ext-js-grid-with-json-data-and-cell-actions.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Ext-js for the first time.</title>
		<link>http://www.masterjrock.com/using-ext-js-for-the-first-time.html</link>
		<comments>http://www.masterjrock.com/using-ext-js-for-the-first-time.html#comments</comments>
		<pubDate>Sat, 31 Jul 2010 23:11:06 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[Ext-js]]></category>
		<category><![CDATA[ext-js]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[Grid.Panel]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=9</guid>
		<description><![CDATA[<p>Last week, I've just added Ext-JS in my toolbox. Ext-js is probably one the best DOM scripting library I know and I'm going to use for all of my Magento projects from now on.</p><p>The data seems a little simple but in a real-world scenario, pages with this data would make it heavy online. Therefore, an alternative way to load data is to use it via AJAX with a json formatted data which will succeed this post, but first on to the basics.</p>]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">L</span>ast week, I&#8217;ve just added Ext-JS in my toolbox. Ext-js is probably one the best DOM scripting library I know and I&#8217;m going to use for all of my Magento projects from now on.</p>
<p>Reading from its examples, below is my basic table grid example using a standard data.</p>
<p>The data seems a little simple but in a real-world scenario, pages with this data would make it heavy online. Therefore, an alternative way to load data is to use it via AJAX with a json formatted data which will succeed this post, but first on to the basics.</p>
<p>First, Download <a rel="nofollow" href="http://www.sencha.com/products/js/download.php" title="Ext-JS Download Page">Ext-js library</a> from their website.</p>
<p>Second, create important header calls:</p>
<pre class="brush:xml">
<link rel="stylesheet" type="text/css" href="[your-ext-js-folder]resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="[your-ext-js-folder]grid-examples.css" />
<script type="text/javascript" src="[your-ext-js-folder]adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="[your-ext-js-folder]ext-all.js"></script>
</pre>
<p>Third, make a javascript call inside the html body (or in the header at your discretion):</p>
<pre class="brush:javascript">

var data = [your json formated array data];

var store = new Ext.data.ArrayStore({ fields: [your field arrays] });

store.loadData(data); // load the var "data"

var grid = new Ext.grid.GridPanel({  //Declare the grid panel
    store: store, //your var "store"
    columns: [your column arrays],
    viewConfig: { forceFit: true}, // force to fit all columns inside the grid
    stripeRows: true, // creates css background on table rows
    height: 210,
    width: 947,
    stateful: true,
    stateId: 'grid', //id of the ext-js var "grid"
    title: '[your header title on top of your table grid]'
});

grid.render('gridView'); // render the var "grid" at the specified html element id
</pre>
<p>And now the <a title="Ext-js Basic Grid" href="http://www.masterjrock.com/wp-content/demos/ext-js/basic-grid.html">demo</a> would be like this.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/using-ext-js-for-the-first-time.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Tabs Content Slider</title>
		<link>http://www.masterjrock.com/jquery-tabs-content-slider.html</link>
		<comments>http://www.masterjrock.com/jquery-tabs-content-slider.html#comments</comments>
		<pubDate>Tue, 22 Jun 2010 11:32:26 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[slider]]></category>
		<category><![CDATA[tab]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=5</guid>
		<description><![CDATA[You can get away just anything with jQuery nowadays. Today’s post is my mimic attempt. And almost every website has a featured content slider or tabbed section of some sort, surely this post will surely be basic asset in my arsenal.  Although, this would not let me to redesign the tabbed links with extra divs with a standard jQuery Tab, I hope someone would give  in a modified  code.]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">I</span> was amazed at how other websites display their featured post to their site. The demo in this article was not a hard-core jQuery as in you see in NowPublic.com&#8217;s front page but this post will surely get me in developing one. &#8211;I hope.</p>
<p>You can get away just anything with jQuery nowadays. Today’s post is my mimic attempt. And almost every website has a featured content slider or tabbed section  of some sort, surely this post will surely be one of my basic assets in my web arsenal.  Although, this would not let me to redesign the tabbed links with extra divs using a standard jQuery Tab, I hope someone would give-in for a modified code of UI Tab.</p>
<p><a title="jQuery Tabs Content Slider" href="/wp-content/demos/jquery-tabs-content-slider/slider.html">Demo</a></p>
<p>I&#8217;ve downloaded a couple of important files:</p>
<p><a title="Get jQuery" onclick="javascript:pageTracker._trackPageview('/outbound/article/jquery.com');" href="http://jquery.com/">jQuery</a></p>
<p><a title="Get jQuery UI" onclick="javascript:pageTracker._trackPageview('/outbound/article/jqueryui.com');" href="http://jqueryui.com/download">jQuery  UI (the core and tabs)</a></p>
<p>I called all the core jQuery javascripts:</p>
<p>﻿
<pre class="brush:xml">
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.tabs.js" type="text/javascript"></script>
</pre>
<p>And now my jQuery UI Tab call: I need it to rotate every 5 seconds, even after a tab click.</p>
<pre class="brush:javascript">
                $('.ts-display').tabs({
                    fx: { opacity: 'toggle'}
                }).tabs('rotate', 5000, true);
</pre>
<div class="ts-display"></div>
<p>And this would not work if I don&#8217;t have the UI Tab CSS class &#8211;very important!!!</p>
<pre class="brush:css">
.ui-tabs {
    padding: 0em;
	z-index: 100;
}

.ui-tabs .ui-tabs-nav {
    list-style: none;
    position: relative;
    padding: 0em 0em 0;
}

.ui-tabs .ui-tabs-nav li {
    position: relative;
    float: left;
    border-bottom-width: 0 !important;
    margin-top:5px;
	margin-left:0px;
	margin-right:0px;
	margin-bottom:0px;
    padding: 0;
}

.ui-tabs .ui-tabs-nav li a div{
	width:131px;
	margin:0 5px;
}

.ui-tabs .ui-tabs-nav li a {
    float: left;
	text-align: left;
    text-decoration: none;
    padding-top:15px;
	color: #555;
	height:75px;
	font-size: 0.9em;
}

.ui-tabs .ui-tabs-nav li.ui-tabs-selected {
    padding-bottom: 0px;
    border-bottom-width: 0;
}

.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a {
    cursor: pointer;
}

.ui-tabs .ui-tabs-panel {
    padding: 0em 0em;
    display: block;
    border-width: 0;
    background: none;
}

.ui-tabs .ui-tabs-hide {
    display: none !important;
}
</pre>
<p>And that&#8217;s it for now. Simple as it may seem, but it knocks to my basic needs and purpose for my past and future projects.</p>
<p>Thanks for reading.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/jquery-tabs-content-slider.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP Digg Style Auction Pagination with SEO</title>
		<link>http://www.masterjrock.com/php-digg-style-pagination-with-seo.html</link>
		<comments>http://www.masterjrock.com/php-digg-style-pagination-with-seo.html#comments</comments>
		<pubDate>Sun, 04 Apr 2010 00:56:50 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[axial url routing]]></category>
		<category><![CDATA[digg style pagination]]></category>
		<category><![CDATA[pagination]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[seo]]></category>
		<category><![CDATA[url friendly]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=15</guid>
		<description><![CDATA[I&#8217;m trying to mimic what was displayed in iCollector&#8217;s pagination. So I came across this Digg style pagination and integrate it with SEO friendly urls. First, thanks to guys at Stranger Studios for this awesome pagination function the have provided. And also, thank&#8217;s to the URL Routing tricks at PHP Addiction for the SEO urls [...]]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">I</span>&#8217;m trying to mimic what was displayed in <a rel="nofollow" href="http://www.icollector.com/Diamond-Coins-Fine-Jewelry-Auction_as17699" title="Auction Digg Style Pagination" target="_blank">iCollector&#8217;s pagination</a>. So I came across this Digg style pagination and integrate it with SEO friendly urls.</p>
<p>First, thanks to guys at Stranger Studios for this awesome <a rel="nofollow" href="http://www.strangerstudios.com/sandbox/pagination/diggstyle.php" title="PHP DIgg Style Pagination" target="_blank">pagination function</a> the have provided.</p>
<p>And also, thank&#8217;s to the <a rel="nofollow" href="http://www.phpaddiction.com/tags/php/url-routing-with-php-part-two/" title="URL Routing" target="_blank">URL Routing</a> tricks at PHP Addiction for the SEO urls that I have integrated with this pagination.</p>
<p>To start off with <a href="/wp-content/demos/php/paging.txt" title="Pagination CSS" target="_blank">iCollectors CSS Styles</a>.</p>
<p>Now my parameters would be a different due to the URL routing function. I&#8217;ve added an auction session ID. Therefore my function would be:</p>
<pre class="brush:php">
function getPaginationString($session, $page = 1, $totalitems, $limit = 15, $adjacents = 1, $targetpage = "/", $pagestring = "?page=")
{
// function body
}
</pre>
<p>And my URL routing axial.commanddispatcher would be:
<pre class="brush:php">
case 'session':
        if ( count($parameter) > 1 ) {
            $_REQUEST['page'] = $parameter[2];
            $_REQUEST['per_page'] = $parameter[1];

            if ($parameter[1] == 0)
                $_REQUEST['per_page'] = 10;
            if ($parameter[2] == 0)
                $_REQUEST['page'] = 1;
            $_REQUEST['session'] = $parameter[0];
        } else {
            $_REQUEST['session'] = substr($parameter[0],0,-5);
        }
            require($base_file.'.php');
        break;
</pre>
<p>So if have the url &#8220;<em><strong>auction/session/17697.html</strong></em>&#8220;, it calls the session.php with a $_REQUEST['session'] id 17697 with &#8220;.html&#8221; suffix omitted, defaults to page 1 and defaults to 10 items per page .</p>
<p>And if have the url &#8220;<em><strong>auction/session/17697/10/2</strong></em>&#8220;, again it calls the session.php with a $_REQUEST['session'] id 17697, at page 2 and still defaults to 10 items per page .</p>
<p>While the url &#8220;<em><strong>auction/session/17697/20/2</strong></em>&#8220;, calls the session.php with a $_REQUEST['session'] id 17697, at page 2 and but with 20 items per page .</p>
<p>Please read my post on how to integrate <a rel="nofollow" href="http://www.phpaddiction.com/tags/php/url-routing-with-php-part-two/" title="URL Routing" target="_blank">PHP Addiction&#8217;s URL Routing</a>. For further reading, please visit at their website.</p>
<p>Your mySQL query in your php script should be something like this.</p>
<pre class="brush:php">
$query = "SELECT * FROM " . DB_PREFIX . "lot WHERE session = '".$_REQUEST['session']."' LIMIT $page, $per_page";
</pre>
<p>Having a <em><strong>lot</strong></em> databse table with fields <em><strong>session</strong></em>, I made a simple query with a <em><strong>session</strong></em> id, <em><strong>page</strong></em> and <em><strong>per_page</strong></em> variables </p>
<p>While having SEO in intact, take notice of my dynamic page titles. all of my $_REQUEST variables is on top of my header template function.</p>
<p>A working example of my <a href="http://www.usfinejewelryauctions.com/auction/session/17697.html" title="iCollector's Auction/Digg Style PHP Pagination">iCollector&#8217;s Auction/Digg Style PHP Pagination.</a></p>
<p>Credits:<br />
<a rel="nofollow" href="http://www.phpaddiction.com/tags/php/url-routing-with-php-part-two/" title="URL Routing" target="_blank">PHP Addiction&#8217;s URL Routing</a><br />
<a rel="nofollow" href="http://www.strangerstudios.com/sandbox/pagination/diggstyle.php" title="Digg Style PHP Pagination" target="_blank">Stranger Studios&#8217; Digg Style PHP Pagination</a><br />
<a rel="nofollow" href="http://www.icollector.com/Diamond-Coins-Fine-Jewelry-Auction_as17699" title="iCollercor" target="_blank">iCollector</a></p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/php-digg-style-pagination-with-seo.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clean URLS via PHP URL Routing Class</title>
		<link>http://www.masterjrock.com/php-url-routing-class.html</link>
		<comments>http://www.masterjrock.com/php-url-routing-class.html#comments</comments>
		<pubDate>Sun, 28 Mar 2010 11:02:12 +0000</pubDate>
		<dc:creator>masterjrock</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[clean urls]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[seo]]></category>
		<category><![CDATA[url dispatch]]></category>
		<category><![CDATA[url routing]]></category>

		<guid isPermaLink="false">http://www.masterjrock.com/?p=22</guid>
		<description><![CDATA[<p>Having SEO in mind when creating and developing websites is very crucial. Therefore, URL router/dispatcher comes to play in creating basic URL friendly urls.</p>
<p>I'm totally fed up with query string especially on list and paginations. Luckily I came across with PHP Addictions's Axial_UrlInterpreter php class using $_REQUEST variables.</p>]]></description>
			<content:encoded><![CDATA[
<p><span class="drop">H</span>aving SEO in mind when creating and developing websites is very crucial. Therefore, URL router/dispatcher comes to play in creating basic URL friendly urls.</p>
<p>I&#8217;m totally fed up with query string especially on list and paginations. Luckily I came across with PHP Addictions&#8217;s Axial_UrlInterpreter php class using $_REQUEST variables.</p>
<pre class="brush:php">
//axial.urlinterpreter.php
class Axial_UrlInterpreter  {
    var $command;
	function Axial_UrlInterpreter() {
		$requestURI = explode('/', $_SERVER['REQUEST_URI']);
		$scriptName = explode('/',$_SERVER['SCRIPT_NAME']);
		for($i= 0;$i < sizeof($scriptName);$i++) {
			if ($requestURI[$i]	== $scriptName[$i]) {
				unset($requestURI[$i]);
			}
		}
		$commandArray = array_values($requestURI);
		$commandName = $commandArray[0];
		$parameters = array_slice($commandArray,1);
		$this->command = new Axial_Command($commandArray[0],$parameters);
	}
	function getCommand() {
		return $this->command;
	}
}
</pre>
<pre class="brush:php">
//axial.command.php
class Axial_Command {
    var $commandName = '';
    var $parameters = array();

    function Axial_Command($commandName,$parameters) {
        $this->commandName = $commandName;
        $this->parameters = $parameters;
    }
    function getCommandName(){
        return $this->commandName;
    }
    function getParameters() {
            return $this->parameters;
	}
}
</pre>
<pre class="brush:php">
//axial.commanddispatcher.php
class Axial_CommandDispatcher {
    var $command;

    function Axial_CommandDispatcher($command){
        $this->command = $command;
    }

    function Dispatch(){
        $base_file = $this->command->getCommandName();
        $parameter = $this->command->getParameters();

        //start your custom switch statement here
        switch ($base_file) {
            case 'session':
                    if ( count($parameter) > 1 ) {
                        $_REQUEST['page'] = $parameter[2];
                        $_REQUEST['per_page'] = $parameter[1];

                        if ($parameter[1] == 0)
                            $_REQUEST['per_page'] = 10;
                        if ($parameter[2] == 0)
                            $_REQUEST['page'] = 1;
                        $_REQUEST['session'] = $parameter[0];
                    } else {
                        $_REQUEST['session'] = substr($parameter[0],0,-5);
                    }
                        require($base_file.'.php');
                    break;
            default:
                    $_REQUEST['404'] = 1;
                    require('index.php');
                    break;
          }
      }
}
</pre>
<pre class="brush:php">
//dispatch.php
include($_SERVER['DOCUMENT_ROOT'].'/axial.command.php');
include($_SERVER['DOCUMENT_ROOT'].'/axial.urlinterpreter.php');
include($_SERVER['DOCUMENT_ROOT'].'/axial.commanddispatcher.php');

$urlInterpreter = new Axial_UrlInterpreter();
$command = $urlInterpreter->getCommand();
$commandDispatcher = new Axial_CommandDispatcher($command);
global $commandResult;
$commandDispatcher->Dispatch();

// A utility function to get the url leading up to the current script.
// Used to make the example portable to other locations.
function getScriptUrl() {
    $scriptName = explode('/',$_SERVER['SCRIPT_NAME']);
    unset($scriptName[sizeof($scriptName)-1]);
    $scriptName = array_values($scriptName);
	return 'http://'.$_SERVER['SERVER_NAME'].implode('/',$scriptName).'/';
}
</pre>
<p>Your .htaccess should contain somethng like this:</p>
<pre class="brush:bash">
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ dispatch.php [L]
</pre>
<p>Whenever you browse a web page with router class. It reads the dispatch url script file first to validate whatever $_REQUEST variable it gathers in the client&#8217;s web browser.</p>
<p>By the way, my root directory in this article is rooted at  http://domain/auction. The first paramter after my root directory would always be the sciprt file then followed by its succeeding paramaters for its purpose.</p>
<p>So if browse http://domain.com/auction/session/17696.html, parameter[0] would be my script file session.php then parameter[1] is my auction session id 1796. Inside my session.php script has a $_REQUEST['session'] which I will use for a database query to display requested auction session id.</p>
<p>Credits:<br />
<a rel="nofollow" href="http://www.phpaddiction.com/tags/php/url-routing-with-php-part-two/" title="URL Routing" target="_blank">PHP Addiction&#8217;s URL Routing</a>
</p>
<p><a href="http://www.usfinejewelryauctions.com/auction/session/17699.html" title="URL Router Dispatch Example" target="_blank">See my working example.</a>. Hope this helps. Enjoy!</p>

]]></content:encoded>
			<wfw:commentRss>http://www.masterjrock.com/php-url-routing-class.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

