A fusion of technology, music, and geekyness.
Currently Browsing: Programming

Easy JSON with CakePHP and jQuery

I am not sure if this is the fanciest way to get the job done but it works REALLY well. What job am I referring to? I am referring to outputting data as JSON in a CakePHP view and then parsing it in a jQuery AJAX response. Its fairly easy to accomplish with the JSON parser provided by json.org. Scroll to the bottom and download/include json2.js.

Controller example:

				$sizeArray = getimagesize('/path/to/really_cool_image.jpg');

				$outputArray = array(
					'file' => 'really_cool_image.jpg',
					'width' => $sizeArray[0],
					'height' => $sizeArray[1],
				);

				$this->set('result', $outputArray);

				$this->render(null, 'ajax');

AJAX View example:

Configure::write('debug', 0);
echo $javascript->object($result);

jQuery AJAX response handler example:

	  function(response, status) {
	  		imageDetails = JSON.parse(response);
	  		imageName = imageDetails.file;
	  }

Selective RSS Plugin for WordPress

We had a client recently request that we embed an RSS feed from a different site inside their WordPress install. This would’ve been very easy considering there are 100′s of RSS feed plugins that will accomplish this task. However, they wanted to only display RSS items that had certain keywords in the title. My initial search found no WP plugins that currently were capable of this. I also tried one of the more popular ones, FeedList, but it used the get_rss() function in the WordPress API. For some reason, this function was not properly parsing the feed they wanted to use, most likely due to it not being a valid feed.

So to make a long story short: I decided to make a quick hack up solution and write my own WP plugin. My only hurdle-like requirement is that it had to work for PHP4 as well because the client is on one of our older servers. I ended up finding a really good example by Ryan Stemkoski. He wrote a perfect function for me to tweak a little and expand upon. I am currently waiting to get approved on WordPress extend so I can host my plugin there. For now, I have created a page here where you can download the plugin.

Note: I haven’t tested this in a more recent version of WP yet but I will be soon. Let me know if you find any bugs!

I also figured I would post the source code in case someone needed a quick and dirty solution with some examples.

rss_lib.php

<?php

/*
* RSS Parsing Function
*
* Original Author: Ryan Stemkoski
* http://www.stemkoski.com/how-to-easily-parse-a-rss-feed-with-php-4-or-php-5/
*
* Slight modifications by Jesse R. Adams (DualTech Services, Inc.)
*/ 

function parseRSS($url) { 

	//PARSE RSS FEED
        $feedeed = implode('', file($url));
        $parser = xml_parser_create();
        xml_parse_into_struct($parser, $feedeed, $valueals, $index);
        xml_parser_free($parser);

	//CONSTRUCT ARRAY
        foreach($valueals as $keyey => $valueal){
            if($valueal['type'] != 'cdata') {
                $item[$keyey] = $valueal;
			}
        }

        $i = 0;

        foreach($item as $key => $value){

            if($value['type'] == 'open') {

                $i++;
                $itemame[$i] = $value['tag'];

            } elseif($value['type'] == 'close') {

                $feed = $values[$i];
                $item = $itemame[$i];
                $i--;

                if(count($values[$i])>1){
                    $values[$i][strtolower($item)][] = $feed;
                } else {
                    $values[$i][strtolower($item)] = $feed;
                }

            } else {
                $values[$i][strtolower($value['tag'])] = $value['value'];
            }
        }

	//RETURN ARRAY VALUES
	return $values[0];
} 

/*
* Convert Raw RSS Parse into concise list of items
*
* Optionally pass in limit (on number of items)
* and/or array list of words to grab items by.
*
*/

function extractRSSItems($xmlArray, $limit = null, $filteredWords = array()) {
	$array = array();
	$regex = null;

	if (count($filteredWords) > 0) {
		$regex = implode('|', $filteredWords);
	}

	foreach($xmlArray['rss']['channel']['item'] as $item) {
		if (!$regex || ($regex && preg_match("/$regex/i", $item['title']))) {
			$array[] = $item;
		}
 	}

	if($limit) {
		array_splice($array, ($limit - 1), (count($array) - $limit));
	}

	return $array;
}
?>

selective_rss.php

<?php
/*
Plugin Name: Selective RSS
Plugin URI: http://techno-geeks.org/selective-rss
Description: Simple Plugin that allows you to embed RSS feed items into Pages or Posts. Optionally allows you to choose how many items to display and allows you to limit items to ones that contain certain words in the titles.
Version: 0.1.0b
Author: Jesse R. Adams (DualTech Services, Inc.)
Author URI: http://www.dual-tech.com/about-dualtech-services/
*/

require_once('rss_lib.php');

function filter_feeds($content) {
	$limit = null;
	$filter = array();
	$url = null;

	$inputTag = preg_match('/\[srss (.+)\]/', $content, $matches);
	$rawArgs = explode(',', $matches[1]);

	foreach($rawArgs as $input) {
                preg_match_all('/^(url|filter|limit)=(.+)$/i', $input, $matches);
                $key = $matches[1][0];
                $value = $matches[2][0]

		if ($key == 'filter') {
			$filter = explode(';', $value);
		} else {
			$$key = $value;
		}
	}

	if ($url) {
		$xml = parseRSS($url);
		$items = extractRSSItems($xml, $limit, $filter);

		$htmlToAdd = '';
		foreach ($items as $item) {
			$htmlToAdd .= '<a href="' . $item['link'] . '" target="new">' . $item['title'] . '</a>' . "<br/>\n";
			$htmlToAdd .= $item['description'] . "<br/><br/>\n";
		}

		$content = preg_replace('/\[srss .+\]/', $htmlToAdd, $content);
	}
	return $content;
}

add_filter('the_content', 'filter_feeds');
?>

Update 06/19: Fixed the way arguments are parsed to be less limiting on possibilities.


CakePHP: Including Models inside your Controller

There are currently three methods for including and using models inside your controller. I am referring to the case when your controller does not belong to a model or or the model is not related to the model inside the controller you are working in. Although this case should be extremely rare, it seems to happen to me a lot. This post is basically a re-summary of Gwoo’s response in the CakePHP Google Groups discussion.

1. Controller::loadModel();
This method actually calls ClassRegistry::init() and saves the instance of the model as a parameter in the controller.

Example:

Controller::loadModel('Car');
$cars = $this->Car->find('all');

2. ClassRegistry::init()
This method creates an instance of the Model and returns it for use.

Example:

$car = ClassRegistry::init('Car');
$cars = $car->find('all');

3. App:import() (not recommended)
This method only includes the file. This requires you to create an instance each time.

Example:

App::import('Car');
$car = new Car();
$cars = $car->find('all');

As you can see this is really simple and basic stuff. However, I felt the need to re-post this information. If for nothing else, I will be using this as a reference point for myself :)

Update 5/27/09: Miles Johnson has a nice write up on this on his blog


CakePHP Character Encoding Checklist

I was having some issues today with character encoding and I thought I’d post about it. There are three elements that you need to make sure you have if you want to properly use UTF-8 character encoding in your Cake app. My issue was that I did not have #2, although adding #1 didn’t hurt either.

1. Database Config

Add ‘encoding’ => ‘utf8′ to app/config/database.php

	var $default = array(
		'driver' => 'mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'user',
		'password' => 'password',
		'database' => 'database',
		'encoding' => 'utf8'
	);

2. Make sure your layout has the charset line in the

	<head>
	 	<?php echo $html->charset(); ?>
	 	Other elements...
	</head>

3. This one is set by default, but make sure App.encoding is set in app/config/core.php

/**
 * Application wide charset encoding
 */
	Configure::write('App.encoding', 'UTF-8');

And thats it!


Peep! A friendly GTD compliant productivity tool for you.


About a year ago Rick (http://www.rickguyer.com) had me read the book Getting Things Done by David Allen. In his book, Allen teaches you how to use his strategies and procedures on managing your tasks (or actions) in a very organized and well thought out fashion. His strategy is unique and calls for a very unique tool to accompany his GTD system. When I originally read his book, Rick and I spent several days searching for a different program, service, or web app that would allow us to incorporate Allen’s GTD system in an electronic fashion. After a solid week of effort I gave up after finding nothing that I felt was easy to use and completely GTD compliant.

Finally, after over a year, we decided to create this perfect GTD compliant web service that will help people, like us, be able to incorporate Allen’s system and become more productive. Peep! is “a simple and easy-to-use tool to help you focus and start getting things done.” I highly suggest you all try it and let me know what you think.

Head over to http://trypeep.com and get started today!


« Previous Entries Next Entries »

Powered by Wordpress | Designed by Elegant Themes