DerekAllard.com

CodeIgniter, Bamboo, ExpresionEngine roundup, August 19

Some interesting items in the past week.

Ed Finkler, the man responsible for the great CodeIgniter podcast PHP Abstract, is at it again.  This time, he’s down in Atlanta offering Intro to CodeIgniter for PHP works ‘07.  Go Ed!  If you’re in Atlanta, find that man and buy him a beer.

I’ve also seen a rise of interest in BambooInvoice recently.  Eric Davis wrote Simple and easy to use invoices - Bamboo Invoice and Customizing BambooInvoice.  Great work thanks.  My favourite quote?

The thing I like most about it is that it provides just what I need to invoice my customers; it does not try to provide accounting, supply chain management, or any other “total business solution”.

And that my friends, is why Bamboo is around.  Thanks Eric.  Nice writeup.  If anyone else has written about Bamboo, please do let me know, I’m always interested in reading those posts.

In ExpressionEngine land, there are a few neat things happening also.  Smashing Magazine, in a writable of the RubyOnRails content management system Mephisto, wrote that ExpressionEngine is the first-class engine for professionals; if you’d like to achieve the highest level of flexibility and have the full control over the outer appearance and structure of your weblogs, EE is the first option you should probably consider.

Also, Les Camacho (our fearless VP, and all around cool guy) started a weekly blog entry called “last week on the forums” where he highlights interesting and notable posts from the ExpressionEngine forums.  One of the ones that really stuck out at me was a plugin by silenz called trunchtml.  Nice work silenz.

Enhanced CodeIgniter Session library

A week ago (August 9th) we quietly added some nice enhancements to the CodeIgniter Session library that I wanted to mention.  You can see these for yourself in the subversion repository (here’s the Session.php library and the userguide page).  The upgrades will be part of the next CodeIgniter release.  Three notables include (in descending order of sexiness):

Configurable time_to_update variable

$time_to_update was a variable hardcoded to 300 (5 minutes in seconds).  After the time to live expired, the CI session class runs sess_update, which does some general maintenance and session handiwork.  While 5 minutes is probably a very good choice for 99% of us, there may be times when you want the update to run faster or slower.  So the update time is now configurable by adding $config[‘sess_time_to_update’] to your config file with the rest of the session preferences.  If you choose not to add it, CI just assumes 5 minutes for you.

Regenerating Session Ids

When a session is created, CodeIgniter (well, all PHP applications really) creates a “session id” and assigns it uniquely to you.  In this manner, data can be exchanged with you without also giving away your session data to other visitors.  CodeIgniter now regenerates your id every time sess_update runs (this is of course what makes the configurable time noteworthy). This provides an additional layer of protection against session fixation.

Flashdata variables

OK, now on to the most impressive addition - Flashdata.  Flashdata are variables that only exist for the next request.  They are mostly useful for “flashing” messages like The person $person was successfully edited, but can extraordinarily useful in the general development of a web application.  In Bamboo I use them to indicate success or failure messages to the user, store whom was edited for dynamic dropdowns, store a client name for assigning of invoices, and other various purposes.  Again… very useful.

Using them is almost the same as using the current session library.

$this->session->set_flashdata('foo''bar'); // a variable that only exists for 1 request
$this->session->flashdata('foo'); // reading a flashdata variable 

There is also a keep_flashdata() function, should you need to preserve from one request to another, perhaps a redirect.

If you’ve used any of the wonderful third party CodeIgniter session libraries, you’ve probably already enjoyed some of these features, and I suspect they will be a welcome addition to your toolkit.  On that note though, I’d like to personally take a moment to thank some of the people who have already done great work in this area. Thanks Dariusz Debowczyk (native session), Oscar Bajner (OBsession), Monte Ohrt ( PHP Session), and Dready (DB Session) for their fine work in this area.

This was not an attempt to re-write the session library, but rather to add in a few commonly requested and useful features.  Enjoy!, and I hope it takes your programming to even higher heights!

Ordering Database results by “random” in CodeIgniter

A recent CodeIgniter bug report had got me looking into the depths of the database results functions of the framework.  Essentially, the orderby() function of CI’s Active Record says that you can sort by ASC (ascending), DESC (descending) or RAND().  Imagine this:

$query "SELECT * FROM table ORDER BY RAND()"

Anyone familiar with PHP probably looks and that and thinks of the native PHP rand() function.  This is pretty neat actually, and I’d never really thought about randomly ordering things.  But on further investigation, it became clear that this code wasn’t as nice as it initially seemed.  Firstly, its non-standard SQL, reducing its portability greatly.  While MySQL uses RAND(), other databases have their own way of doing things:

So then, how would one randomly order their database results?  Read on for my solution…

Giving your Helpers a little Help

CodeIgniter is one of the most flexible, powerful, unobtrusive frameworks you could choose to use. It’s so useful in many ways, including pre-existing convenience libraries (I can’t live without the email library anymore), plugins (for handy little tools such as javascript calendars and CAPTCHA creation) and the appropriately named “helpers”.

In the world of CodeIgniter libraries, plugins and helpers, the libraries are Rock Stars. They get most of your attention, they do most of the heavy lifting. They date super-models, party in Europe, and return on Monday to keep your application humming along (sometimes Tuesday… you know those darned unreliable rock stars). They can be extended, overwritten, and you can create your own, wholly new libraries just for your application. Wow. No wonder super-models want to date them.

One of the most handy aspects of libraries, is that you can create a libraries folder in system/application/libraries, and leave the existing CodeIgniter libraries untouched. This makes upgrading to newer versions of CI a breeze, as you never need to worry about going in and re-implementing all the changes you made to a library.  From the userguide:

As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries folder.

And while libraries are doing all this work, we’re left with the humble, but infinitely handy helper. Here’s what the userguide has to say about helpers.

Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category.

Makes them sound like one-trick ponies; but they are not. Helpers, while not quite as flexible as libraries, are tremendously useful. They are written procedurally, instead of object oriented (as the rest of CodeIgniter is). And while they can’t be extended as libraries can, a little known fact is that they can be overwritten. Better yet, is the method in which you’d override them. Much like libraries, the trick lies in creating a folder underneath system/application for helpers. Then, when CodeIgniter loads helpers, it looks first in your application/helpers folder, and only if that folder can’t be found does it then fall back on the default system/helpers folder. So you can add your own helpers, or overwrite existing ones.

Here’s a case study. In BambooInvoice I use the date helper’s timespan() function to determine exactly how overdue an invoice might be. My problem is that the default timespan() function keeps tabs down to the second of the span of time. When tracking invoices, I don’t care how many hours, minutes and seconds have passed, only how many days and weeks (or months if you have a really bad-paying client ;)) So for use in Bamboo, I want that helpers default output changed. The solution, to remove or comment out those lines of the helper.

But the problem with modifying the system helper is that in the next upgrade, that helper gets overwritten again. Since I use BambooInvoice as part of my testing codebase for vetting new CodeIgniter code, I tend to overwrite these files a lot. This then required carefully keeping track of what helpers were modified, and introduced some other problems. A preferable approach would be to simply make a copy of system/helpers/date_helper.php in application/helpers. Now, the application helper will be loaded preferentially, and I can modify to my hearts content without ever fearing I’ll accidentally overwrite my changes.

Application based helpers are a handy feature indeed. There have been discussions about changing the procedural structure of helpers to allow for extending and over-riding, but for now, the simplicity of helper functions are preserved, and you can easily maintain your own modified versions.

How are you using CodeIgniter helpers? If you’ve modified any of the base helpers, or created your own, I’d love to hear about it here.

CodeIgniter Language Packs

As I’ve outlined before on this blog, BambooInvoice has gone international.  I’m grateful to have many wonderful people step up and offer to translate.  Of course, that meant that I also needed the language packs for each of the respective languages.  In looking through the current language pack collections I was disappointed to see that many of the packs have disappeared from the net.  In fact, I needed a Romanian pack, and it wasn’t available, but Marius Visan stepped up to the plate, and re-translated the whole of CodeIgniter for me into Romanian.

So in order to prevent these from unexpectedly dropping off again, I thought I’d post the 5 language packs I’m currently using in Bamboo to my site.  If you have made others and would like them added here, let me know and I’ll be happy to update this post.

CodeIgniter 1.5.4 released

From the CodeIgniter news:

CodeIgniter 1.5.4 Released
Version 1.5.4 is primarily a maintenance release.  For a list of all changes please see the Change Log.  If you are currently running CodeIgniter please read the update instructions.

A maintenance releaseRick, the master of understatement as usual.  All of us busted our butts, but particular praise should go to Derek and Paul, who (among many other things) rewrote the input library and significantly increased its awesomeness.  In fact, security in CI on the whole is a considerable step up.

Here are some other notables:

OK, I guess that fits the definition of maintenance release, then why did it feel like so much work?

The autoloadable custom languages is almost directly resulting from the renewed effort to internationalize BambooInvoice.  Much more is coming, and CI development is once again in our wheelhouse.

Are you pirating CodeIgniter?

In a recent chat with Lisa and Nevin we were trading funny stories along the lines of “can you believe I was asked $odd_request” and so forth.  This made me remember an interesting story involving the illegal pirating of CodeIgniter.

The request was made through my site contact form from a Hotmail address, so clearly they were at least aware of my site, and might even be regular readers?  It might even be you!

Are you a CodeIgniter using Wordpress?

So the gist of this post boils down to me asking “why”.  Presumably you’re using Wordpress to blog.  If you are using it as a pseudo-cms, then you already feel the pain.  What if there was a blogging platform that was superior to Wordpress in security and functionality, and also would give you expertise in a framework that could double as a full-fledged Content-Management-System that you could use commercially with your clients/customers, and was tightly integrated with CodeIgniter… would you be interested?

Then why aren’t you using ExpressionEngine?

Rick Ellis (The “Ellis” in Ellislab and all around grand pu-ba) recently announced what has been widely speculated in the community for a long time, that ExpressionEngine is getting integrated very tightly with CodeIgniter.  This leaves me with the aching question: As a CodeIgniter programmer, what does Wordpress offer you?  Many of us (CI programmers I mean) keep a personal blog where we discuss CodeIgniter and related developments.  When deciding on a blogging platform, there are several good options, but it seems that there are 2 common choices; (1) roll it yourself (this is how I started) or (2) use Wordpress.  I’d like to argue right now for a third, and better, option - use ExpressionEngine.

Learning PHP with CodeIgniter

Every now and then, the question comes up of if its a good idea to learn PHP before one learns CodeIgniter, or after one learns CodeIgniter.

I teach technical training for 2 universities, a college, and do a lot of corporate training, so I often find people who are just starting out and wanting to pursue a tool.  For a long time my knee-jerk advice was “learn the skill first, then come back to the tool.”  That said… the longer I think about it, the more I can see how learning PHP through a framework like CodeIgniter could be really useful. So here is my current position on the topic.

If you don’t know PHP and want to learn, then learn it at the same time as you learn CodeIgniter

alternating comment styles

I've been asked how I acheive the alternating comment styles in my blog. When this blog was custom built on CodeIgniter, I used alternator() in the string helper. It looked like this:

<?php foreach ($post_comments->result() as $comment): ?>     <div class="comment<?= alternator(' even', ' odd');?>        <p><?php         if ($comment->comment_author_website) {             echo anchor ($comment->comment_author_website, $comment->comment_author_name);         } else {             echo $comment->comment_author_name;         }         ?> wrote on <?= date ('F jS, Y @ G:i', $comment->comment_date);?></p>         <?= $comment->comment_body;?>     </div> <?php endforeach; ?>

When I switched my blog over to ExpressionEngine a few months ago, I decided to change my strategy a bit, and use the tools EE makes available for me. Specificly, the {switch} tag for comments.

{exp:comment:entries sort="asc"}     <div class="{switch="even|odd"}">         <p>{url_as_author} wrote on {comment_date format="%F %d<sup>%S</sup>, %Y @ %G:%i"}</p>         {comment}     </div> {/exp:comment:entries}

I find it ever bit as intuitive as pure PHP, and I love the convenience shortcuts like {url_as_author} (Hyperlink pointing to the URL (if it exists) with the author name as the link title. If the URL does not exist simply the name is returned).

I still have all the legacy code (of course) from the custom written blog app, and while I don't want to release it wholesale, I'd be happy to field any specific questions about any part of it.