Django has an excellent function that assists in working with models, get_object_or_404. As Python functions tend to, the name of this function is pretty descriptive: we attempt to get an object (from the model) and if we can’t we throw a 404 error to the user.

We can achieve a rather similar effect, and clean up our code, within a CodeIgniter controller. In the following example, we’ll load a model and attempt to retrieve a record, throwing a 404 error if the request fails:

The other key component to this is the model itself, ensuring a value interpreted as FALSE is returned when an object can not be found. Here’s a quick sample:

NULL (along with FALSE, 0, and an empty string) are all interpreted as FALSE by PHP in a loose comparison (== as opposed to ===). When assigning a value to a variable using the OR operator, PHP will assign the first value that is interpreted as TRUE or the last value within the condition. Since our model will return NULL if a record is not found, PHP attempts to assign the return value of show_404() to that variable. This function doesn’t return a value though, instead it send your application’s ./errors/error_404.php (with appropriate headers) to the user – the exact functionality we desire!

Facebook just announced their Facebook Social Plugins, a collection on one-liner tools that allows your users to engage and promote your content using Facebook. One of these “plugins” is the infamous Facebook Like button – which I have added to every post within this blog.

Below is the code I used, which is placed within the post loop. Most of this is the standard code you get directly from Facebook, the relevant portion to look at is the urlencode(the_permalink()) bit as well as some of the styling (which will differ based on your own theme).

7 Comments »

ErkanaAuth

As the entire CodeIgniter community runs over to Mercurial and Bitbucket, thanks to EllisLab’s huge announcement earlier today it seemed only fitting to get ErkanaAuth hosted over there as soon as possible.

Honestly, I’ve been wanting to do something like this for a lot of my open-source work for a long time; I just keep putting it off. I love the distributed environment for collaborating on projects like this, because you guys probably have a lot of great ideas for this library! Now, you can contribute as well!

Go ahead: check out the repository, fork it, make some changes and send me pull requests so I can look over them. You can check out my original post for my thoughts in where I see this library headed.

EllisLab has just announced they have transitioned away from Subversion to Mercurial and are hosting the CodeIgniter 2.0 source on Bitbucket.

I did a quick glance through the source and here are some of the things I immediately noticed in CodeIgniter 2.0 (this isn’t a comprehensive list, just what I find the most exciting):

  • Scaffolding has finally been completely removed.
  • The codeigniter directory has been renamed to core and houses most of the absolute necessities. [source]
  • System-wide plugins are gone (they were mostly worthless to begin with).
  • There’s a new Javascript library that features a driver system, similar to the database libraries. jQuery is currently supported but expect to see more. [source]
  • A driver library has been added, to assist developer in creating their own driver-backed libraries. [source]
  • You can now enable/disable individual sections of the profiler (it’s also it’s own class, rather than being part of the output library).[source | source]
  • There’s a new security library that features CSRF protection and becomes the new home for XSS filtering. [source]
  • The Input, Upload and XML-RPC libraries have received new features and make use of the security library.
  • The Cookie helper now utilizes the Input class. [source]
  • The application directory now contains a third_party directory, I presume would take the place of the old plugins directory. [source]

I’m most excited about the new Security library but can’t wait to see how this release shapes up! What are you most looking forward to in CodeIgniter 2.0?

Edit: Phil Sturgeon and Elliot Haughin have provided their run-downs of CodeIgniter changes as well. One of the biggest changes I missed was the fact that CodeIgniter 2.0.0 functionality is not guaranteed to work in PHP4 and by CodeIgniter 2.1.0, legacy features will no longer be guaranteed to work in PHP4 either.

SimplaSimpla, the theme you see here was released just over 4 years ago. Since that time WordPress has deprecated a number of its template tags – the functions theme developers use to bring WordPress’ functionality into their designs.

I took it upon myself to run through this theme, looking for any of the deprecated functions and replacing them with their updated versions. Although the theme still works, today, with these deprecated functions that functionality could cease at any moment.

Surprisingly, the majority of the theme has withstood the test of time. I only notice two issues: the get_settings() tag in header.php and the wp_list_cats tag in sidebar.php.

The two snippets below reflect the altered portions of the code, bringing Simpla in-line with WordPress 2.9.2 (although I believe the actual deprecation took place many, many versions ago).

In the header, get_settings() is used to make the title of the blog link back to the home page. This snippet makes use of the new get_option() function, which allows us to provide a default value in the second parameter (I just hard-coded in what my blog URL should be) which would be used in-case this option went mysteriously missing from our database. For an added bonus, I’ve included the rel=”home” microformat as well.

Our sidebar was using the wp_list_cats() function. We’re going to replace that with the newer wp_list_categories() function. We’ll pass this function a string of arguments, which will allow us to display the number of posts within each category and suppress the default heading and <ul></ul> wrapper that the function places around the list (since we’re using our own header).

ErkanaAuth

ErkanaAuth, although in a very alpha form, is simple to use and already extremely powerful. Protecting a portion of your website behind the authentication system is as easy as one-line, a call to the library’s required() method.

In this example, we are protecting an entire controller behind the authentication library:

When a method within this controller is called, the user’s session will be validated. If the user has not authenticated they will then be forwarded to your application’s accounts controller, where your login and user creation methods should reside.

To protect individual methods, just call the required() method in the first line of the method you want to protect.

OpenIDEarlier this morning I made a complaint on Twitter concerning how OpenID URLs are typically long and hard to remember – I was specifically referring to Google’s OpenID URLs. Sure, there are other providers available, and to be perfectly honest I have accounts with some of the more popular (WordPress, Yahoo, etc.), but my Google account is the one provider that gets used on a daily basis.

Chris Harrison brought me back on track telling me I should just use my own domain as my OpenID provider. Honestly, this required more effort than I wanted to exert but I started looking around for simpler solutions. As it turns out, there are two meta tags you can add to the header of your site (openid.server and openid.delegate) that will essentially “forward” any OpenID requests to your OpenID provider. This would allow me to make a quick change on my domain, not worry about maintaining the software that actually serves as the provider, yet still reap all the benefits.

Unfortunately, Google doesn’t support the openid.delegate meta tag…

Fortunately, one of Google’s very own App Engine demos does serve as an OpenID provider and allows you to delegate to their server. App Engine also allows developers to easily include authentication in their application by simply using the user’s Google Account – which is exactly what this demo application does. The end result: I authenticate with my Google Account to this App Engine demo and it serves up OpenID authentication on my domain’s behalf.

Check out the OpenID Provider demo and login to your account. After you’ve logged in the application will tell you what your OpenID URL is, which you could use on sites like StackOverflow to authenticate. If, on the other hand, you want to use your own domain as your OpenID URL, take this information, edit the HTML meta tags below, and toss them into the header of your very own website:

Edit: As Eric Harrison and Carsten Pötter mention within the comments, Google now supports OpenID on your individual profile pages. Check out John Panzer’s tutorial.

Regular ExpressionsCodeIgniter comes with an excellent Form Validation library right out of the box. This library features a number of validation and preparation functions that are executed on posted form fields when the run() method is called. If you need additional functionality, it is also very easy to add your own validation/preparation functions to your application, without modifying any of the underlying CodeIgniter codebase.

If you have a decent level of experience with Microsoft’s Excel, you may have had to develop a custom cell format from time to time. This basic format syntax provides a very loose, but functional, method of defining the format of the input you expect. In this tutorial, we’ll define a new form field validation rule (called matches_pattern) that excepts one argument that will define the pattern we want the user’s input to match. Our goal is to make something very simple to use, but moderately powerful, so we’re going to stay away from having to use regular expressions within our validation rules. Instead, we’ll create a set of replacement characters to use within our rules instead: # to represent a number, ? to represent an alphabetical character and ~ to represent any character.

These characters will allow us to validate a user’s input matches specific cases. For instance, phone numbers could be forced to match (###) ###-#### or a date field could be forced to match ##-##-#### (MM-DD-YYYY).

The first step in extending CodeIgniter’s Form Validation library is to create our own Form Validation class within our applications libraries/ directory. By default, the prefix for your own extending classes is MY_, so we’ll create libraries/MY_Form_validation.php and stub out the following code:

We've now extended the default Form Validation library and we have a function, called matches_pattern() that we can call from our set_rules() method. Let's start fleshing out this method and translating our characters into their regular expression equivalents:

We're now using str_replace() to translate our special characters into their regular expression equivalents. Finally, we run through preg_match() and return a boolean as to whether the user input ($str) matches. You may wonder why we're just not returning the value of preg_match(). Unfortunately, preg_match() returns a 1 or 0 (at least on my development server) and CodeIgniter expects an explicit boolean, therefore we run it through the conditional really quick.

Our last step is escaping some of the standard regular expression special characters. In regular expressions, characters like (, ), [ and many others have special meanings. We don't want to make use of these special meanings within our patterns though; if our patterns contains an ( we literally want to match on that character (rather than capturing a successful match). We'll implement this by modifying our character arrays and replacing these special characters with their escaped versions:

The final step in this process is to define the error message that is reported when our validation function returns FALSE. This is done by defining your own language file within your application at language/english/form_validation_lang.php. The content within this file will be appended to CodeIgniter default form_validation_lang.php file:

The %s within this language definition will be replaced by the field name in which you include this rule. To use our new rule, we just append it to the rule set for any of our fields within our controller:

It's very easy to create your own validation rules. If you find yourself writing callback functions to do the same things over and over, consider bringing that function out into your own Form Validation library. The matches_pattern() function we wrote here provides an easy-to-use, yet simple, way to match a specific pattern - just remember to inform your users of what that pattern is! If you wanted, you could an include another %s within your language definition that would insert the specific pattern in the error message.

Is there a topic you want me to write an article on? Today’s your lucky day! I’ve added the GetSatisfaction Skribit widget to the right-hand border of this page.

A quick click of the widget will allow you to submit ideas, a question, a problem or give me some head-bloating praise. Feel free to use and abuse but remember this is a public means of communication, if you need to contact me privately you can always email at webmaster@michaelwales.com.

Edit:
Chris Harrison pointed out Skribit to me and it is much better suited for this purpose.

Google Dropping Support for IE6

February 4th, 2010

Web BrowsersAs web developers we typically fulfill a number of roles: developer, designer, marketing, SEO. Of all these roles nothing is more frustrating than the designer role, primarily due to the evil that is Internet Explorer 6. Thankfully, Google has taken a stance, primarily fueled by the recent Chinese attacks, and IE6 is going down.

Last week, on the Official Google Enterprise Blog, the Senior Product Manager of Google Apps announced that as early as March 2010 Google will start phasing out support for older browsers. The official lineup Google recommends consists of Internet Explorer 7.0+, Mozilla Firefox 3.0+, Google Chrome 4.0+ and Safari 3.0+.

Google also sent an email to all Google Apps for Domains administrators yesterday that clarified some concerns people had: this isn’t just for the enterprise users. Users of the standard GMail and Google Calendar will see functionality dropping off on older browsers as well. This really shouldn’t come as a surprise. As developers, would you expect Google to maintain two separate codebases, one of which has inherent flaws that consistently introduces security vulnerabilities? I didn’t think so…

Is this the nail in the coffin that is Internet Explorer 6? I think so! With such a drastic change from one of the industry leaders, a company most people couldn’t dream of living without in this day, older browsers have no choice but to die off. Most people using IE6, or various other older browsers, aren’t doing so by choice – they are in enterprise environments in which they are not able to upgrade. These companies are now being told by one of the largest providers of software they use on a daily basis, the time is now! If more companies, and even developers like us, took a stand like Google is we would see an end to the 8+ year browser lifecycle that IE6 has enjoyed.