Extending CodeIgniter Parser to support Objects

CodeIgniterI really like codeIgniter, since it’s super lightweight, and its learning curve is super small. You can get to build a whole website within just a couple days, even with database support.

I’ve written myself a e-commerce website in just two weeks, without having previous knowledge on the technology. Now, let’s get to business.

What happens when you’re writing a view (php based), and you need to display a variable?. Well, you’ve got, essentially, two options. To begin with, you can simply invoke the php ‘echo’ routine, by doing something like this:

[cc lang=”php”][/cc]

Now, if you wanna keep your code really clean, you can rely on CodeIgniter built in parser. How do you implement it?… super simple…:


1. Initialize the Parser Library:

[cc lang=”php”]$this->load->library(‘parser’);[/cc]

2. Replace the ‘<?php echo $blog_title; ?>’ routines with the following syntax:

[cc lang=”php”]{blog_title}[/cc]

So far so good. Now… here’s something interesting. What happens if you wanna print an object’s property? or an object’s method?. Well, CodeIgniter doesn’t support that scenario. It will only work with strings, and with arrays (of strings). So… i’ve extended a bit the library, in order to support ‘printing object’s properties’.

You can download right here my extended version of the parser. We won’t be analyzing the code i’ve written. It’s not complex, and you’re invited to run a diff between the original, and my patch.

Now… how do we use it?. Simple…

1. Install the sf_parser library

You should copy the ‘sf_parser.php’ file to ‘/application/libraries/sf_parser.php’. That’s it. No more no less. Simplicity is one of the things i love the most about CI framework.

2. Initialize the sf_parser library

Instead of initializing the CI’s default parser, we’re gonna need to load our custom library. We can achieve that by doing the following:

[cc lang=”php”]$this->load->library(‘sf_parser’);[/cc]

3. Use the new syntax!

The goal of this library is to enable you (the user!) to print any object’s properties, or getter’s results. Which means that… instead of using the following syntax, in your view.php file:

[cc lang=”php”]get_title();>[/cc]

You can now do something far more elegant… which looks something like this:

[cc lang=”php”]{blog:get_title}[/cc]

If you found it useful… if you found a bug… or if you’ve extended it further, i’d love to hear from you!

%d