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: Beginning your Tumblelog

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.

In my previous article, we went over the basics of CodeIgniter. Now we’re going to actually build something. For this four-part series we’ll build a tumblelog using many of the features CodeIgniter has built-in as well as third-party libraries.

A tumblelog is more then just a blog, it’s your lifestream; your tweets, your bookmarks and your blog posts. To keep this series simple we’ll be building a basic Tumblelog that allows you to post blog posts, grab your delicious bookmarks and show your tweets.

To begin, we must first install CodeIgniter.

Requirements
  • PHP 5
  • CodeIgniter
  • Apache
  • MySQL 5

I also suggest you have

  • A MySQL Admin Tool. I love Querious http://www.araelium.com/querious/ but if you’re flyin’ on the cheap, Sequel Pro (http://www.sequelpro.com/) or the MySQL Admin Tool (especially for Windows) work well.
  • A great text editor. I use Textmate; e-Text Editor for Windows works well, but really it’s your preference.
  • MAMP or WampServer for easy local hosting.
Getting Started

The first thing we need to do is to make sure we have the CodeIgniter framework. To do this download the latest files from the CodeIgniter website. There’s a giant download button that should service you well. Then, simply copy these files to the root of your server. In a production environment, you would not want to leave the “system” folder in the site root, but instead move it below. For our purposes (and for brevity) we’ll skip over this and refer you to the CodeIgniter Forums for best practices.

If you’ve copied the files over and are looking at your server, you should see something like this:

               

Welcome Screen for CodeIgniter

The next step is to rename the application folder to the name of our application. For this project I’ve asked the clever gnomes to come up with a name and they have returned with “tumbleupon.” So go into your system folder that came with the the CodeIgniter framework and rename name application to tumbleupon. When we do this, we have to change the value of the $application_folder variable in the index.php located in the site root. On line 43 of index.php edit this line:

$application_folder "application"


To match your application folder name. In our case this line becomes:

$application_folder "tumbleupon"
Setting up the database

I’m going to use a GUI to create a database, and if you know the command line or MySQL and are comfortable creating your own database, please do so. I’m going to create a database called “ci_tumbleupon.” I’ll be using the root user for this example, but, please, in a production environment create a separate user with limited permissions. I refer you to this great article on MySQL practices.

Now there are a couple more configuration items to setup. Go to /system/tumbleupon/config/database.php and enter your hostname, database, username and password. For my example, I’m using a local install of MAMP, so it looks like:

$db['default']['hostname'"localhost";
$db['default']['username'"root";
$db['default']['password'"root";
$db['default']['database'"ci_tumbleupon"

If you would like to use a different database driver, it’s up to you, but MySQL is what we’re doing here.

Creating your homepage controller

CodeIgniter is controller-heavy, so it makes sense to start from the controller’s perspective and work from there. Fortunately for us, CodeIgniter comes with a homepage controller called welcome.php in your controllers directory under applications. We are going to rename the controller tumble_upon.php and this will control our homepage.

Then, we will change our code from:

<?php

class Welcome extends Controller {

    
function Welcome()
    
{
        parent
::Controller();    
    
}
    
    
function index()
    
{
        $this
->load->view('welcome_message');
    
}
}

/* End of file welcome.php */
/* Location: ./system/tumbleupon/controllers/welcome.php */ 

to:

<?php

class Tumble_upon extends Controller {

    
public function __construct()
    
{
        parent
::__construct();
    
}
    
    
public function index()
    
{
        $this
->load->view('home');
    
}
}

/* End of file tumble_upon.php */
/* Location: ./system/tumbleupon/controllers/tumble_upon.php */ 

What changed?

  • We changed the class name to reflect the filename. This is important, as well as capitalization. The underscore is not, you can use whichever naming method you prefer.
  • Functions now properly declare their access levels. “public” instead of just “function”. The reason for this is to follow good coding practices. Eventually, we will use multiple scopes (“private” and “protected” are the others) to perform functionality that only our class or objects need to access.
  • The End of file and Location at the bottom. This is important to remember and easy to forget. Once again, just for implementing good coding practices.
  • Changed function Welcome() and parent::Welcome() to __construct() and parent::__construct(). Constructor methods are a little advanced for our purposes, but there is abstraction with the PHP 5 __construct() that may come in handy when we modify this code later.
  • We changed the $this->load->view method parameter to home. This loads the view we’re going to make in the next step.
  •                                          

There you have it your first Controller, but it’s not going to do much without…

Your first view.

Create a file in the views directory called home.php and paste the following code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
>
<
html>
<
head>
    <
meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <
title>Welcome to TumbleUpon</title>
    
</
head>
<
body id="home" onload="">
    <
h1>{hello:world}!</h1>
</
body>
</
html

Yes, it’s a “hello, world” reference, but hey, why break convention? We’ve now created our first view, which the Tumble_upon class will load, but if you go to your homepage you’ll see this:

CodeIgniter 404 page

Uh oh. You broke it. No, actually you’re not following CodeIgniter’s URL pattern. So, in order to correctly view your site you need to go to yoursiteurl.com/index.php/tumble_upon/ (See the URLs link above on how to remove index.php). It works!

Wait, but isn’t this supposed to be the homepage?

Yes, it is, and to do this we need to override CodeIgniter’s default URL handling. Fortunately, CodeIgniter makes it easy. All we have to do is go to /config/routes.php and change

$route['default_controller'"welcome"

to

$route['default_controller'"tumble_upon"

Load up your site’s homepage and you should see your hard work.

Coming up…

In the next article, we will build the blog functionality of our Tumblelog.

Posted on Jun 01, 2009

Filed Under: How-To, CodeIgniter, Web Development

Matthew Pennell06:19 on 06.01.2009

Nice start, Kenny. Is it worth mentioning why you’ve chosen to use PHP5 (i.e. which features you’re going to use that rely on it)? New CI users might not realise that they can also use CI even if their host doesn’t provide PHP5 support.

Kenny Meyers06:30 on 06.01.2009

Hey Matthew,

Great Question!

There are lots of reasons for using PHP 5 and why I chose it.

1. I think anything older then IE6 shouln’t be taught as a best practice in 2009.

2. PHP 5 offers better Object-Oriented Support

3. PHP 5 is a better iteration of the language

4. While I understand CodeIgniter is PHP 4 compatible, I view these articles as training new people or front-end people. This means making sure they’re up to date on the latest, best practices of which PHP 4 is not.

5. If people don’t have PHP 5 on their hosting service I hope it encourages them to get it. Mosts hosts I know of now offer that option.

6. PHP 4 needs to die.

7. If their host doesn’t carry it, they can develop and learn locally, then switch hosts.


Hopefully that answers your question!

Cheers,
Kenny

Jeff06:33 on 06.01.2009

Ok, that was easy enough. When is the nest one due?

Kenny Meyers06:35 on 06.01.2009

Depends on Mr. Ryan-to-the-Irelan’s schedule and mine but we’re going to try to keep them very close together.

Philip Zaengle05:47 on 06.02.2009

Great article, thanks for taking the time to write it! Looking forward to the next installment.

Dave17:32 on 06.02.2009

As you’ve changed your application folder name. You need to do a little extra house keeping and update your end of file comment.

/* End of file tumble_upon.php */
/* Location: ./system/tumbleupon/controllers/tumble_upon.php */

Kenny Meyers17:45 on 06.02.2009

Dave you strike again! I even re-doubled my efforts for fear of the other article’s slip-up. I live in ever present fear of your comment on an article I write to show my inadequacy!

I’ve emailed Ryan, thanks again for your help.

Cheers,
Kenny

Jared Cornwall20:34 on 06.04.2009

Always like to find good articles on CodeIgnter. Look forward to the rest of the series.

Anne Hathaway21:24 on 06.04.2009

What I need to know is why you write like a second grader?

Thanks!!

Kenny Meyers21:37 on 06.04.2009

@Anne Hathaway

Ouch!

If you could give me corrections, that’d be great.

Loved you in “Rachel Getting Married”.

Cheers,
Kenny

Anne Hathaway22:10 on 06.04.2009

Kenny,

Thanks! Like you, I love my work! Its the most important thing to me. Its what gets me out of bed in the morning!

I’ll work up a list of corrections and post them here. My mom was a schoolteacher you know!

Thanks again!

Edemilson Lima16:42 on 10.31.2009

Where can I find the next part?

Herb10:12 on 01.31.2010

SWEET! great article, and it really helped.
(coming from a noob)

nashigoovert18:29 on 10.19.2010

игра старый замок музыкальные детские игры порно флеш игры online календарь игр первого дивизиона warcraft tft скачать игру играть игру школа волшебниц скачать игру naruto ntsd казино игры скачать бесплатно офисные игры 2008 сборка 2 компьютерные порно игры бесплатно
<a >похожие игры world goo</a>
<a >обитаемый остров игра обзор</a>
<a >игры типа шарики</a>
<a >игра машинах ночью</a>
<a >игры sony ericsson k5молодые</a>
<a >браузерная игра ферма</a>
<a >бесплатно игра русский бильярд</a>
<a >онлайн казино игровые автоматы адмирал</a>
<a >игровая площадка порка</a>
<a >онлайн игры надо скачивать</a>
<a >игра заработало 4</a>
<a >дидактические игры уроках естествознания</a>
<a >скачать игру русский биллиард</a>
<a >коды игре worms armageddon</a>
<a >секреты игры бирже</a>
<a >игра iron man 2</a>
<a >java игра танчики 2008</a>
<a >игры морскую тематику</a>
<a >идеальный мир онлайн игра скачать</a>
<a >логические игры pc</a>
<a >мини игры 2009</a>
<a >прикольные java игры скачать бесплатно</a>
<a >скачать игры двоих</a>
<a >конец игры фильм</a>
<a >лайн игра острова</a>
<a >прохождение игры симулятор системного администратора</a>
<a >игра fifa 2009 сети</a>
<a >игры со шреком</a>
<a >сохранения игры dead space</a>
<a >игра ктохочет стать миллионером</a>

скачать программы взламывания игр <a >скачать логические игры</a> игровой бот irc <a >unreal tournament 2004 сетевая игра</a> новые прикольные игры <a >flash игра mortal kombat</a> универсальный кряк игр алавар <a >игра скуби ду 3</a> скачать игру сталкер исполнитель желаний <a >игра sims 2 naruto</a> crfxfnm игры xbox 360 <a >gta коды прохождения игры</a> игра half life флеш <a >интернет магазин игр компьютера</a> скачать cd игры <a >flash игры мультиплеер</a> купить игру sims 3 <a >поиграть карты</a> игры персонального компа <a >бассейн игровой центр морской</a> самоучитель игры соло гитаре <a >flash игры отбей атаку</a> флеш игры двоих онлайн <a >игра создай дом</a> маленькие игры регистрации <a >взлом онлайн игры seafight</a> книги разработке игр <a >запуск игр windows 7</a> пройти игру макс пейн <a >скачать самые крутые игры</a> скачать игру driver <a >печем пиццу играть онлайн</a> игра метро <a >soccer скачать игру бесплатно</a> скачать игру подземелье драконов <a >самоучитель игры балалайке</a> игра гарри поттер мобильного <a >молодые подвижные игры улице</a> рпг игры стрелялки <a >игра одень звезду</a> детские флеш игры онлайн <a >скачать игру загадки царства сна</a> crysis warhead обзор игры <a >жестокие эротические игры</a> игра street rage <a >игры xbox live</a> онлай игры регистрации <a >виртуальные игры молодые</a> взломанные игры n gage 2.0 <a >скачать шаблоны игровых сайтов бесплатно</a> игра need speed 2 <a >игры nokia n 72</a> java игры jad <a >игра хочет стать хакером</a> перс ру флэш игры <a >эротичные аниме игры</a> swat 4 игра сети <a >где купить настольную игру монополия</a> программа запуска java игр <a >виртуальная экономика игра</a> скачать игру настольный теннис бесплатно <a >игра секс со знаменитостью</a> бизнес игры девочек бесплатно <a >список бесплатных онлайн игр</a> развивающие игры студентов <a >секс игры регистрации</a> скачать игру command conquer 3 <a >star trek voyager игра</a> игры nokia e 66 <a >игры комп бесплатно</a> эротические игры играть онлайн бесплатно <a >игра менеджер скачать бесплатно</a> сервер игры сфера <a >коды игре мадагаскар 2</a> игры чистого разума <a >поиграть прям интернете драки</a> скачать тренеры игр <a >флеш игры играть лайн</a> игры уроках физики <a >создание игр програмирования</a> игра cd flock <a >nokia 6270 игры скачать бесплатно</a> бесплатные игры форум <a >стратегические бесплатные браузерные онлайн игры</a> сервера игры доту <a >ремонт игровых аппаратов</a> sacred 2 игра интернету <a >прохождение игры секреты твоих кошмаров</a> игры алавар скачай играй <a >скачать игры бесплатно ps1</a> скачать java игру counter strike <a >скачать патч игры ведьмак</a>

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

Hosting by EngineHosting

ExpressionEngine Training Videos and Screencasts