Building with CodeIgniter: Using Libraries
by Kenny Meyers
Editors Note: I’d like to welcome back Kenny Meyers as a guest author on EE Insider. Kenny is a web developer at Seattle, WA based Blue Flavor. He loves ExpressionEngine & CodeIgniter for their “less is more” approach and the ability to generate good, clean standards-compliant markup. He will be writing a series of articles on building a simple web application with CodeIgniter.
So now that we have Building a blog with CodeIgniter, in order to make it lifestreamy, to make it tumble we need to add our delicious and twitter links to it. To do this, we’re going to employ an area outside of the MVC structure called “Libraries.”
What are Libraries?
A CodeIgniter library is technically a PHP class, much like our model and controller. However, a library servers a function outside of the controllers. You’ve already used on library, the database library to create the blog model. One of CodeIgniter’s greatest features is that it’s very loosely coupled. What does this mean? It means that you can take out almost every single component and the system will still function. This allows for greater flexibility in the size and execution of your application.
Another great benefit of having loosely coupled systems is that you can add other people’s libraries to the mix. In our case we’ll be doing just that. In fact, we’ll be using two libraries from Elliot Haughin.
The first library is Elliot’s Twitter library. To download this library, please go here and click on “Download Twitter API CodeIgniter” at the bottom of the page. Take the time to look at the documentation and you can see this lovely piece of code:
$this->load->library('twitter');
$this->twitter->auth('username', 'password');
$timeline = $this->twitter->call('statuses', 'friends_timeline');
Once you load this library, this is all you will need to get tweets. Three simple calls. Beautiful.
The second library is from Elliot as well, and is based off of the SimplePie RSS parser technology. We’ll be using this for our delicious links, and while there are better ways to grab links, it’s important to use RSS in a website at least once. To grab that library, go here and scroll down to download.
If you look at the documentation there you can see this code:
$this->load->library('simplepie');
$this->simplepie->set_feed_url('http://feeds.haughin.com/haughin');
$this->simplepie->set_cache_location(APPPATH.'cache/rss');
$this->simplepie->init();
$this->simplepie->handle_content_type();
$data['rss_items'] = $this->simplepie->get_items();
When you are finished, simply move the files: The Simplepie.php
file and the two .php
files in the Twitter libraries
folder to /tumbleupon/libraries/
. You’ve just installed two libraries! Have a beer and take a break. Also, people like Elliot who give great libraries away for free deserve your money. You can support him buy buying some screencasts here. Perhaps enjoy it while you are drinking your beer?
Making functions.
So as you saw above, there are some simple function calls in order to get your tweets and bookmarks going. If you’re going to use Tweets on multiple pages (as we are) then there are three ways to go about it. One, add private functions to your Blog controller for getting tweets and bookmarks. Two, create a universal helper function that you can use to grab them. Three, modify the library classes or extend them with additional functionality. We’re going with option one for simplicities sake.
In PHP 5, a private function is a function per object. Other objects, including members of the same class can not use them. They’re useful for encapsulation, and keeping people’s dirty hands off your code.
Our first private function is called get tweets, place this at the bottom of your blog controller replacing username and password with your twitter username and password.
private function _get_tweets($count = 5){
$this->load->library('twitter');
$this->twitter->auth('username', 'password');
return $this->twitter->call('statuses/user_timeline', array('count' => $count));
}
This function does the following
- Sets a parameter of count which defaults to 5, if you want to request more change the
_get_tweets()
method in theindex()
function to_get_tweets(10)
or_get_tweets(11)
- Loads the twitter library which we downloaded
- Calls the authorize method with two parameters, your username and password and verifies you have an account
- Use the call method to request data from the Twitter API (in our case the user_timeline) and gives the call method an array of options (in our cause a count of 5).
- Then it returns the data from twitter as an object.
As you can see the magic of well-built libraries is they make doing complex tasks very simple. All it took was three lines for us to load our tweets.
Now let’s get our bookmarks.
First, create a directory in /tumbleupon/cache/
called ‘rss’ and set its permissions to 777. When that is complete, let’s build our _get_delicious()
function:
private function _get_delicious($count = 5){
$this->load->library('simplepie');
$this->simplepie->set_feed_url('http://feeds.delicious.com/v2/rss/kennymeyers?count='.$count);
$this->simplepie->set_cache_location(APPPATH.'cache/rss');
$this->simplepie->init();
$this->simplepie->handle_content_type();
return $this->simplepie->get_items();
}
Again, this is a very simple function. We set a parameter of $count with a default of 5 which you can change at any time.
- First, we load the simple pie library
- Second, we use the set_feed_url method to setup our RSS feed’s location
- Third, we use the
set_cache_location
method to use the folder we just created. Simplepie is lovely in that it automates this type of caching. - Fourth, we initiate the object.
- Fifth, we use the
handle_content_type()
which takes care of determining the encoding, etc. - Then finally we return an object of delicious links with the
get_items()
method.
There, that’s all we need, now let’s call it in the controller index
function.
Add the following code below $this->load->model
:
$entries['delicious_links'] = $this->_get_delicious();
$entries['tweets'] = $this->_get_tweets();
We have now added the delicious_links
& tweets
objects to the entries array, which is being served up to our index.php
view. So, open up /views/blog/index.php
and add the following below the </body>
tag.
<?php foreach ($tweets as $tweet) { ?>
<div class="tweet">
<h2><?php echo $tweet->user->name; ?></h2>
<img src="<?php echo $tweet->user->profile_image_url ?>" title="<?php echo $tweet->user->name ?>" title="<?php echo $tweet->user->name ?>">
<p><?php echo $tweet->text ?></p>
</div>
<?php } ?>
<?php foreach ($delicious_links as $bookmark) { ?>
<div class="link">
<h2><a href="<?php echo $bookmark->get_link(); ?>"><?php echo $bookmark->get_title(); ?></a></h2>
</div>
<?php } ?>
So, much like entries before it, it’s just looping through the values of the object. Let’s look at each closely.
<?php foreach ($tweets as $tweet) { ?>
<div class="tweet">
<h2><?php echo $tweet->user->name; ?></h2>
<img src="<?php echo $tweet->user->profile_image_url ?>" title="<?php echo $tweet->user->name ?>" title="<?php echo $tweet->user->name ?>">
<p><?php echo $tweet->text ?></p>
</div>
<?php } ?>
For each library you use, they generally construct objects to be returned to the view. This means that like controller objects and classes there are methods much like index()
and properties like $tweet->user->name
(which should be apparent). This allows for a lot of flexibility in formatting and controlling your view.
- In our twitter case, we are doing a loop through the tweets array which has 5 tweet objects.
- We’re then asking the tweet object for the user and then the user’s name
- We created an image element and asked for the profile image URL
- and finally we’re just asking for the tweets text.
It’s very, very simple.
Delicious links, however, are done a little differently because the library is a little different.
<?php foreach ($delicious_links as $bookmark) { ?>
<ul class="link">
<li><a href="<?php echo $bookmark->get_link(); ?>"><?php echo $bookmark->get_title(); ?></a></li>
</ul>
<?php } ?>
What’s the big difference? We’re calling object methods instead of properties. It is always important to look at the library you are building with and see what it creates, and how to access the information you need.
First, we use the get_link
method to get the URL of the link from our RSS feed. Second, we get the title of the link as we have saved it in delicious.
That’s it. You now have twitter links and bookmarks. In our next series we’re going to add a ton of polish and an admin back-end interface. Should be awesome and thanks for reading!