Build Your Portfolio With CodeIgniter

You know about web design, and you’ve decided to use a PHP framework to get you started. With the availability of so many great open source software projects out there – like Zend Framework, CakePHP, and Drupal, WordPress – it’s easy to be overwhelmed. Each of those projects has their merits and drawbacks, but my favorite is CodeIgniter – it’s powerful, lightweight, and flexible. There are several  tutorials on CodeIgniter. Here’s a introductory video tutorial that uses PHP4 syntax. The things this tutorial uses PHP5 syntax.   For the sake of  brevity, I’m going to assume you’ve already installed it. I’m going to explain how to build a portfolio site using CodeIgniter.

Lets think about the typical layout of a portfolio – homepage, about, contact, services, work – most of which are probably static pages. The “work” page could be database driven, depending on how comfortable you are using databases. For this post, I’m going to assume its static, and leave it as an exercise for you to make it dynamic. Let’s get started, shall we?!

Here’s how CodeIgniter reads it’s urls by default:

example.com/class/function/ID

You want your URLs to be simple. The homepage should be “/”, contact “/contact”, about  “/about”, and services “/services. For the moment, we’re not going to consider the Work pages. If you create your controllers using the default URL setup, you’ll have 4 controllers to start. In each one of those, you would create a method called index(). This is the method that gets called automatically when you don’t specify a 2nd segment for your URL.  While that will work, there is a better way, that will makes things easier for you.

Lets  start by opening your favorite text editor, and create a file called Main.php. In this file we’ll create your controller. it should look like this:

<?php
class Main extends Controller {
    public function __construct(){
        parent::__construct();
    }

    public function index(){
        echo "Homepage";
   }
}
?>

Save this to your CI_INSTALL/application/controllers directory. To run go to example.com/index.php/main where example.com is your site. But wait, we wanted to call it ‘/home’ . To make this happen we’re going to use a magical feature of CodeIgniter – routes! Ok, maybe it’s not magical, but it sure is great to use. So you’re aware it’s a very bad practice to use echo statements in your controller. This gets fixed shortly.

In your CI_INSTALL/application/config is a file called routes.php that we need to edit. The default controller should be set to “main”, like below.

$route['default_controller'] = "main";

While we’re editing the routes.php file, lets also add the following lines below the default controller and scaffolding settings.

// Custom routes for my site
$route['about'] = "main/about";
$route['contact'] = "main/contact";
$route['services'] = "main/services";

Now that we’ve made that update, lets go back to our controller main.php. Lets update the index action to use a view script instead of the echo statement. The code below will load the file home.php in the CI_INSTALL/application/views directory.

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

That takes care of how to load the home page. Now lets create the methods for the other routes.

public function about(){
    $this->load->view('about');
}

public function contact(){
    $this->load->view('contact');
}

public function services(){
    $this->load->view('services');
}

When you call your views scripts this way, you’ll need to have all the page HTML – from DOCTYPE to your closing “html” tag. You can call multiple view scripts, so I suggest you make two more  – header.php and footer.php – as an exercise. For now, create them with all the required HTML. For the about page, run it in your browser like this

example.com/index.php/about

Now that we’ve done a majority of the pages now, we just need to do the ‘work’ pages. We made this one separate because this one could be more involved than the other pages, depending how you’d like to implement it,  so its best to create a separate controller. Since this will be responsible for displaying pages of our work, we’re gonna want a little more power.  We’ll have two different different URLs – /work (which will be an overview page), and /work/client-name to display each client project on it’s own page. The overview page is easy. It works just like the homepage. In your CI_INSTALL/application/controllers directory, add the following code.

<?php
class Work extends Controller {

	public function __construct(){
		parent::__construct();

	}

	public function index(){
		$this->load->view('work_index');
	}

}
?>

Now that you’ve created the controller, now create a view script in CI_INSTALL/application/views called work_index.php and add the html you want to display.

For the client pages, we’re going to add a little more code. Our goal here is to have one page that we can re-use for every client. The first thing we need in a new method that we’ll call client. In the method we’ll create an array to associate the client id with their information.

public function client($clientId){

    $data = array(
        'foo' => array('title' => 'Foo Title',
                 'hero' => '/images/foo/hero.jpg',
                 'altText' => 'foo logo')
        ,'bar' => array('title' => 'Bar Title',
                 'hero' => '/images/bar/hero.jpg',
                 'altText' => 'bar logo')
    );

    $this->load->view('work_client', $data[$clientId]);
}

What’s happening above, is the third segment that comes in is passed in as the argument to the method. To paraphrase: the value of $clientId is whatever appears the in the third url segment. $clientId is used to get the corresponding information to send to the page. Below is a simple view file that will process that uses the information for the client.

<html>
<head>
<title><?php echo $title; ?></title>
</head>

<body>
    <h1><?php echo $altText ?></h1>
        <img id="hero"
             src="<?php echo $hero?>"
             alt="<?php echo $altText ?>" />
	<p>this is some information about the project.
You should update the controller with the information that you would like
 to appear here.</p>
</body>
</html>

Above we mentioned that we want our client urls to be example.com/index.php/work/client-name, but if you’ve been paying attention, you currently need to type example.com/index.php/work/client/client-name for the page to show up. Now I’ll show you how to fix that – by returning to our magical friend routes.php. Add this to the file just below the routes you added earlier.

$route['work/(:any)'] = "work/client/$1";

At this point everything should be working fine. But you’re probably thinking “how do I get rid of the index.php from my URLs?” To do this you need a .htaccess file in the root of your website. paste the lines below into it on your server.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|css|js|images|robots\.txt)
# this line adds index.php to the URL so CodeIgniter can process it.
RewriteRule ^(.*)$ index.php?$1 [L]

Throughout your site, now you can write URLs like /about. The Apache web server will use the htaccess file make the URL be index.php/about so CodeIgniter can handle it properly.

Ok. That should be enough to get you started. Take the time to write your feedback in the comments below. If this helped you, great! If there’s something you think is missing, that is also good to know.

8 Responses to “Build Your Portfolio With CodeIgniter”

  1. natebot says:

    Nice introduction.

    Good choice I think on the routing urls to a single controller for a small site.

    I find there is a balancing act to play between intuitive urls, slim and fast loading controller files, and ease of maintaining/extending your code. The routing class certainly helps mediate that.

    • Andrew Woods says:

      @natebot Thanks! The use of routes is a nice feature and it’s not always obvious to new CI users. I like features that are elegant, as they usually lead to more concise code.

  2. Nice i too will try 2 Build my Portfolio With CodeIgniter, if any problems wil ask you

  3. I am in the process of trying to put together my online portfolio with CodeIgnitor. Definitely a new way of thinking for a designer like me. Great tutorial, thanks!

  4. drew says:

    Nice work, most tutorials seem to push a programatic approach as opposed to a functional one – thinking about it from the view or presentation side as opposed to “this is a controller, this is a model, this is a view” and getting lost.

  5. Nick Yeoman says:

    You forgot the most important part that differentiates CI to other frameworks: documentation!

  6. David Coe says:

    Thank you for publishing this. It’s given me a very useful and different insight into CodeIgniter.

    As a total beginner to the subject I found a couple of parts of your tutorial confusing and missing. Hopefully a couple of amendments will help other beginners on their way.

    (1) You ask to save the first file as Main.php. I found when doing this the file wasn’t found. Dropping the capital letter and renaming it to main.php solved this error.

    (2) You make no reference to create another view .php file for the detailed client page. A file called ‘work_client’ needs to be created in the ‘views’ directory. This contains the php echo statements.

    (3) It’s probably worth noting that foo and bar in the array are the client names. and that to test everything is working they should visit either example.com/index.php/work/client/foo or example.com/index.php/work/client/bar

    I know some of this is elementary but this makes the tutorial appeal to a wider demographic.

    Good work on the tutorial. I found it very useful.

  7. David Coe says:

    Thank you for publishing this. It’s given me a very useful and different insight into CodeIgniter.

    As a total beginner to the subject I found a couple of parts of your tutorial confusing and missing. Hopefully a couple of amendments will help other beginners on their way.

    (1) You ask to save the first file as Main.php. I found when doing this the file wasn’t found. Dropping the capital letter and renaming it to main.php solved this error.

    (2) You make no reference to create another view .php file for the detailed client page. A file called ‘work_client’ needs to be created in the ‘views’ directory. This contains the php echo statements.

    (3) It’s probably worth noting that foo and bar in the array are the client names. and that to test everything is working they should visit either example.com/index.php/work/client/foo or example.com/index.php/work/client/bar

    I know some of this is elementary but this makes the tutorial appeal to a wider demographic.

    Good work on the tutorial. I found it very useful…