CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

RSS Feeds, Fast and Easy

For my first entry, I am going to talk about how to create an RSS Feed on your website. RSS (Really Simple Syndication) is a format used to publish frequently updated works such as blogs or featured products. RSS defines a set of XML elements that are used to describe a channel or feed of information. An RSS feed is comprised of two parts, first is the metadata describing the channel and second is the records that make up the elements of the feed. RSS feeds allow your sites visitors to access the information on your site using software that reads these feeds. This will allow your site's visitors to stay up-to-date on the information on your site.

CakePHP allows for easy integration of RSS feeds into existing controller actions through the automatic router extension parsing. This allows us to specify what type of response we want from a URL through adding the proper extension to the URL such as http://www.yoursite.com/entries.rss. This alerts the router that your are asking for RSS formatted data in return. In addition, CakePHP has an RssHelper class that can be used to output parts of the metadata and elements in the feed through an easy to use helper.

Preparation

Before we begin making the feed we must alert the router that we want to allow for extensions to be parsed in the URL and that we want it to accept .rss as a valid extension. In your sites router file we add the following:

	Router::parseExtensions('rss');

Also for CakePHP to work it magic we must also have the RequestHandler in our controller's $components array. Now the router knows that we would like to parse urls that end in .rss as requesting RSS formatted responses. The next step of preparation is to add a default layout for rss feeds on your site. When you request a different format response the layout that is rendered will be selected from a sub-folder with the same name as the format. So in this case we would need a folder called /rss in the layouts folder in our CakePHP install. The view class will search for a file that has the same name as the layout that would be rendered if you were just rendering the html. In most cases this is the default.ctp layout file in the main layouts directory, but because we are requesting the response in RSS format we must add a default.ctp layout in the /layouts/rss/ sub-directory. This layout is our default RSS Feed layout.

	echo $rss->header();

	if (!isset($channel)) {
		$channel = array();
	}
	if (!isset($channel['title'])) {
		$channel['title'] = $title_for_layout;
	}

	echo $rss->document($rss->channel(array(), $channel, $content_for_layout));

Here in the layout our RssHelper shines through. We use the method RssHelper::channel() which generates the element and associated metadata elements. The $content_for_layout variable contains the output from the view. These then get passed to the RssHelper::document() method, which wraps the RSS document in the respective elements.

Controller

The controller needs no modification in the case of a simple RSS feed. This is because we are only adding a second view that is xml/rss to the action. The same data is used in both views and because CakePHP automatically sets the correct response type we don't need to tell it to render the correct view and layout for RSS. Here is the action method in the EntriesController for a basic view sorted by a published_date field and showing only if it is published.

	public function index() {
		$this->paginate['Entry'] = array(
			'conditions' => array('Entry.published' => 1),
			'order' => 'Entry.published_date DESC');
		$this->set('entries', $this->paginate());
	}

If you do have code that is specific for only the RSS view you can use the RequestHandler::isRss() to see if the action was called with the request for xml/rss formatting on response. This method returns a boolean value based on if the .rss extension was parsed in the URL.

	if ($this->RequestHandler->isRss()) {
		// RSS feed specific code goes here
	}

Note About Channel Metadata

It may feel right to put your metadata information in the index method in the controller, using Controller::set() to send the information to the views. This is inappropriate and is one of the most common snags that we have seen in the CakePHP community with creating RSS feeds. That information which is passed in the layout file to the RssHelper::channel() method should be set in the view using View::set() which will set the $channel variable for the layout in the view.

Views

As we had to put the layout in a subdirectory of the layouts folder we also need to create a view for the index action for the blogs controller. This is done by creating a directory /views/entries/rss/ which will hold our view file that will generate the RSS to render. You will need to add your RssHelper to the list of helpers in your controller so that it is automatically loaded in the view and the layout.

Our view begins by setting the $channel variable for the layout, this contains all the metadata for our RSS feed.

	$homeUrl = $html->url('/', true);
	$this->set('channel', array(
		'title' => __("Daniel's Recent Articles", true),
		'link' => $homeUrl,
		'description' => __("Most recent articles from Daniel.", true),
		'language' => 'en-us',
		'image' => array(
			'title' => 'Recent Articles from Daniel',
			'url' => FULL_BASE_URL . $this->webroot('/img/rss_feed_image', true),
			'link' => $homeUrl));

First we get the URL link for the website home that we will use for the links. Also we set the title, description and image to use for the RSS feed icon. By setting the channel variable using View::set() we are providing the layout the information to render the RSS feed's metadata elements.

The second part of the view generates the elements for the actual records of the feed. This is accomplished by looping through the data that has been passed to the view and using the RssHelper::item() method. The other method you can use, RssHelper::items() which takes a callback and an array of items for the feed. (The method I have seen used for the callback has always been called transformRss(). There is one downfall to this method, which is that you cannot use any of the other helper classes to prepare your data inside the callback method because the scope inside the method does not include anything that is not passed inside, thus not giving access to the TimeHelper or any other helper that you may need. The RssHelper::item() transforms the associative array into an element for each key value pair.

	foreach ($entries as $entry) {
		$postTime = strtotime($entry['Entry']['created']);

		$entryLink = array(
			'controller' => 'entries',
			'action' => 'view',
			'year' => date('Y', $postTime),
			'month' => date('m', $postTime),
			'day' => date('d', $postTime),
			$entry['Entry']['slug']);

		// This is the part where we clean the body text for output as the description 
		// of the rss item, this needs to have only text to make sure the feed validates
		$bodyText = preg_replace('=\(.*?)\=is', '', $entry['Entry']['body']);
		$bodyText = $text->stripLinks($bodyText);
		$bodyText = Sanitize::stripAll($bodyText);
		$bodyText = $text->truncate($bodyText, 400, '...', true, true);

		echo  $rss->item(array(), array(
			'title' => $entry['Entry']['title'],
			'link' => $entryLink,
			'guid' => array('url' => $entryLink, 'isPermaLink' => 'true'),
			'description' =>  $bodyText,
			'dc:creator' => $entry['Entry']['author'],
			'pubDate' => $entry['Entry']['created']));
	}

You can see above that we can use the loop to prepare the data to be transformed into XML elements. It is important to filter out any non-plain text charictars out of the description, especially if you are using a rich text editor for the body of your blog. In the code above we use the TextHelper::stripLinks() method and a few methods from the Sanitize class, but we recommend writing a comprehensive text cleaning helper to really scrub the text clean. Once we have set up the data for the feed, we can then use the RssHelper::item() method to create the XML in RSS format. Once you have all this setup, you can test your RSS feed by going to your site /entries/index.rss and you will see your new feed. It is always important that you validate your RSS feed before making it live. This can be done by visiting sites that validate the XML such as Feed Validator or the w3c site at http://validator.w3.org/feed/.

Latest articles

Simplicity is important - here’s why

When it comes to web design, simplicity is not valued enough. Simplicity is important - but why? Simplicity reduces navigation confusion, makes the website look more sophisticated and can help in increasing site conversions (sign ups, contacts). All too often, web designers tend to miss the point of simplicity and over do the amount of information given on a single page - the need to get everything across at once can seriously hinder how much a website visitor is able take in. Over complicated pages can lead to higher than average bounce rates or lower on-page conversions. We thought we’d share with you some top tips to simplify your website.

  • Keep things along the 80-20 rule
    • Use the Pareto principle which is that 80% of the effects come from 20% of the causes. This means taking away as much as you can from your design that will not lead to any type of conversion. Take things back to the bare essentials and make those work properly
  • Embrace few colors in your theme
    • Does a monochrome color scheme work for you? If not, try out as few colors as possible. Work towards a design that requires less effort for your website visitor to process. Fewer colors will also give your site a sleek, classic look
  • Keep copy short and sweet
    • Embrace compelling copy but keep things shorter and to the point. Make your point quickly and keep things easy-to-read by sticking to a few key points. Use shorter sentences, and keep paragraphs to a maximum of 3-4 sentences for easy reading.
  • Fix your navigation
    • Often many sites have over complicated and lengthy navigation options. Remember to include navigation to your list of things to simplify today. Keep important and key pages in your navigation bar. Remove excess clutter and keep all navigation menus visible. Other key things to keep in mind is the use of universal icons as well as ensuring a sitemap in your footer - these are all standard items that visitors look for.

How Much Does it Cost to Design a Site?

If you are in the market for a website or application, it can sometimes be daunting. Being unsure of where to start, which development firm to use or how much the whole process is going to cost you can be truly overwhelming. And then there are those horror stories of others, who selected a developer based solely on cost (the cheapest quote perhaps) and ended up majorly down the hole with their budgets, while owning a unfinished website. Whether you are in the market for a website application with a specific outline and goal, or have a rough idea of what you need your application to do, how do you go about finding the best selection for you? And then how do you know that whoever you select is going to deliver what you want and in the time frame that you need it? And then, not knowing how to code yourself, you can land up frustrated at not understanding the process - especially if your development team gives you the runaround. At CakeDC, we are committed to a transparent workflow - we've created our own git workflow (MIT license) and we've used it successfully with our clients for 3+ years and dozens of projects. We use it to accelerate growth and innovation providing the highest quality application development. What sets CakeDC apart from others is that our experts listen closely to your needs. Second, we formulate a roadmap of milestones based on your specifications. Third, we offer guidance while delivering the highest quality results in a fraction of other developer’s time, by doing things The Right Way™ So how much is it going to cost you? Well this is of course dependent on what you project scope includes, however, we will work with you in determining the best package to suit your requirements. You can check out all of our rates and packages here. Ready to get your project started? Reach out to our experts today to see how easy it can be to get your application up and running.

What your website users are trying to tell you

Every visitor to your website has a goal in mind - this may not be a conscious goal, but they are visiting your site for a reason. So listening to your users feedback is key to meeting their expectations! As a business owner, be sure to keep these in consideration and as a developer, be sure to pass these recommendations through to your clients. What are some things that users are trying to tell you and how do you find out? What and why is it Often people forget about the basics and fail to include what their product, service or business is. By excluding this vital information there will be users who will not know what the purpose of the page that they have stumbled upon is, but what to do next - and therefor bounce quickly off of your site. Where is your pricing information? If you are trying to sell something - a product or a service - be sure to include the price information as this is used by your visitor to determine their next action. Even if you are providing resources in return for their details, it is important to be clear. Where are those testimonials or reviews? Have others tried it People like to know that whatever they are investing money into is worth it - reviews or customer testimonials help to show your visitors what you can do. Be sure to add this information in a way that is easy for you visitors to find. Where can I sign up or contact you Another vital piece of information that many often forget is to let your visitors know how to signup and contact you. Perhaps you have chosen to hide your contact information due to spam bots or other issues faced, however, if you are in the business of recruiting clients, then be sure to have some form of contact information easily available to your visitors.
Not sure if you are missing anything? CakeDC, the experts behind CakePHP, offer a range of services including consulting, guiding you through the best practices with your CakePHP application.

We Bake with CakePHP