movie icon image

ExpressionEngine How-to Articles

Topics range from beginner to advanced, but are all born out of real world, professional, day-to-day use of ExpressionEngine. Need more information? Get training videos and ebooks on ExpressionEngine from Mijingo.

Building with CodeIgniter: Using Libraries

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 the index() 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!

Posted on Jun 26, 2009

Filed Under: How-To, CodeIgniter, Web Development

Colin11:05 on 06.29.2009

_get_tweets() and _get_delicious() probably belong in separate models. But for something this lightweight, having it in the controller is fine.

Kenny Meyers11:24 on 06.29.2009

@Colin

Absolutely they do, and more importantly, they could use their own models to save them to the database, etc. For the scope of these articles I made it really simple, maybe deceptively so. But it’s real purpose was to show how to use libraries. Thanks for the feedback.

Victor07:29 on 06.30.2009

where exactly are you storing the simplie.inc file? you post says - “simply move the files to Simplepie.php file “

i am not sure what that means .. thx ..

Kenny07:31 on 06.30.2009

Victor, this is stored in the /tumpleupon/libraries/ folder.

steve05:21 on 07.01.2009

Victor, rename Simplepie.inc to Simplepie.php and copy that file to your application/libraries/ folder.

Neil Bradley12:33 on 09.03.2009

If you were to create seperate models for twitter and delicious, how would you reference these in views/blog/index.php to display the results?

Would you also need to create additional controllers for twitter and delicious?

Kenny Meyers12:36 on 09.03.2009

Neil,

You could just use the $load->model(“Twitter”) functionality to grab the model’s abilities in your controller functions.

Cheers,
Kenny

Kenny Meyers12:38 on 09.03.2009

Follow up:

$this->load->model();

Would be the correct function.

Tahsin Hasan21:58 on 07.17.2010

Hello,

you can also see the scripts of

1. tweetsigniter - a twitter codeigniter library.

2. Extended My Input library - you can also see the weakness of current Input library of codeigniter here.

3. Codeigniter Advanced Layout Library - The advanced layout library for codeigniter. you can also see what are the short comings of current layout libraries.

Thanks. stay connected with tahSin’s gaRAge.

Thanks.

Tahsin Hasan.

Tahsin Hasan09:33 on 10.01.2010

Hello,

See the twitter codeigniter library tahsin garage.

nobBibliaibia03:21 on 01.10.2011

heyesure
specters
<a >tamsulosin women</a> 
dugout
cracks
<a >proscar hair</a> 
freuds
applying
<a >cheap protonix</a> 
brezzi
ofnila
<a >köp viagra sverige</a> 
reminisce
nivea
<a >generic omeprazole</a> 
cobains
litrc
<a >viagra naturale erboristeria</a> 
troydeneen
conferencesa
<a >baclofen tablets</a> 
dickblick
repo
<a >ibuprofen vs naproxen</a> 
cloaker
maltsberger
<a >effexor without prescription</a> 
francois
doubleheader
<a >how long does seroquel stay in your system</a> 
amonghave
jessamine
<a >naproxen 500mg</a> 
roboword
greening
<a >estradiol 1 mg</a> 
employmenta
clubsarah
<a >cymbalta for anxiety</a> 
спортзале
biomes
<a >prednisone cats</a> 
torneterms
aciphex
<a >norvasc generic</a> 
mineropar
westmontreal
<a >buy amlodipine</a> 
breathaway
mediawelcome
<a >buy plavix without prescription</a> 
racesterling
fleischman
<a >generic for fosamax</a> 
dnas
tycho
<a >clarithromycin 500 mg</a> 
nimmo
reliancethe
<a >biaxin medication</a>

Post a Comment
Commenting is not available in this section entry.

Hosting by EngineHosting

ExpressionEngine Training Videos and Screencasts