Getting Started With CodeIgniter: Part 5 - Loose Ends

So you understand the basics of MVC. You get the Active Record and all that craziness. You have CI up and running, maybe even with some basic controllers and views. You're on your way. At this point, it's the details that start to get confusing. Where do assets (CSS, JS, images, etc.) go? How do I know if this piece of code belongs in a model or a library (or a helper)? How can I change the way URLs are displayed? If this sounds like you, you're in the right place my friend.

Site Structure

You're given a pretty good bit of wiggle room as to where you want everything to go. I'm going to give you my recommendation based on lots of reading on CodeIgniter's security and personal experience on what is easiest to work with. Here is the layout of Capsize Designs' site:

PHP:
  1. + public_html
  2.     + css
  3.     + js
  4.     + img
  5. + application

As you can see, the system and application folders are siblings of the web root, not children. That way (as I talked about in "Part 4 - Security"), only scripts running on my server can reach them. This makes direct scripting virtually impossible for any malicious user. All you have to do is update "index.php" to change the route to your system and application folders. In my case, it looks like:

PHP:
  1. /*
  2. |---------------------------------------------------------------
  3. | SYSTEM FOLDER NAME
  4. |---------------------------------------------------------------
  5. */
  6.     $system_folder = "../system";
  7.  
  8. /*
  9. |---------------------------------------------------------------
  10. | APPLICATION FOLDER NAME
  11. |---------------------------------------------------------------
  12. */
  13.     $application_folder = "../application";

I've obviously moved the application folder out of the system folder. This is a very popular thing to do among CI users just because it makes navigation a little simpler, and updating CI is easier as you don't have to worry about overwriting your application folder. This, in my opinion, should be the default. You might also rename these two folders to something a little more secure.

Asset Management

If you're wondering the best way to reach the CSS, image, and JS folders on my example site structure, here's your answer: THE HTML HELPER! This is a tiny and very useful little tool for replacing many HTML tags with PHP functions that do some of the work for you. For example, if you want to have 4 page breaks in a row, just do something like:

PHP:
  1. <?=br(4)?>

Instead of manually typing each break. It makes the code look a little cleaner and easier to manage. There are also functions for unordered and ordered lists, non-breaking spaces (one which I use a good bit), and even headings.

However, we're going to focus on the img() and link_tag() functions. These are how we will reach our image and CSS files at the web root. Without these functions, you'd have to do something like this:

PHP:
  1. <link rel='stylesheet' href='<?=base_url()?>css/style.css' type='text/css' />

TIP: The base_url() function (which is defined in the URL helper which you should be autoloading for its usefulness) outputs your web address which you specified in config.php.

Instead of all that nonsense, just pull out one of these:

PHP:
  1. <?=link_tag('css/style.css')?>

The link_tag function will automatically append base_url() and outputs a standard link tag for the browser. The img() function does pretty much the same thing except with an image tag instead of a link tag. As for javascript, the masterminds behind CI are working on an integration of jQuery and CodeIgniter ($this->javascript->fade_in() anyone?). Until then, you're stuck using standard script tags.

NOTE: If you're working on a large site and find yourself going crazy with assets everywhere, check out AssetLibPro to make your life a little simpler.

Custom Libraries and Helpers

One of the great things about CI is the active community developing things to use in your CI web apps. Just about every day somebody announces something new they have developed on the forums that you can use for free. Most of these things will be libraries. All you have to do is copy the library over to your application/library folder, and then either load them in a controller ($this->load->library('something');) or have the autoload from application/config/autoload.php.

Often, these things provide you with a bunch of related functions you can call in your controller (or model or even view but that's nasty). For example, a typical site may have a library for dealing with user authentication (ReduxAuth or FreakAuth Light perhaps), a blog (InkType is powered by CI), a CMS (Blaze!), an administrative backend (CodeExtinguisher is up there), you get the idea.

For a pretty good list of libraries, helpers, plugins, and everything else, CodeIgniter's got you covered.

Models vs. Libraries vs. Helpers

We all know what Models, Views and Controllers are (if you don't then check out part 2). You probably have a basic understanding of Libraries and Helpers as little groups of related functions that help you out. But if you want to create one (say, a file of functions which help you make CAPTCHAs), which folder will it go into? Is it a model, a library, or a helper? No fear, young one. I will enlighten you.

Let's start with Helpers. A helper file usually is centered around a certain category (such as HTML, Email, Forms, etc.). The difference is that they are not written in object oriented format. You simply load the helper and then call a function on the helper. If your bit of code seems like it doesn't need to be object oriented, then it should probably be in a helper.

But you're designing a class for user authentication which almost certainly should be object oriented (i.e., you want to create a user instance and then do something do it - edit, delete, whatever). Should this be a model or a library? The answer to this one isn't as cut and dry. It's more whatever is your style. I personally like to put anything involving database logic in a model, and all code snippets that don't involve the database in a library. But that's just me. You do whatever tickles your fancy.

URL Management

CodeIgniter's URL structure is pretty nice (i.e., www.website.com/controller/function). But say you want to display user profiles at www.website.com/username. How can you make this work! Just use a route. That "routes.php" file has been chillin' in application/config for some time now not getting any game time, but it doesn't have to be like that!

I'm not going to go into it very deeply except to say that it's there and it's well documented. This is really useful and totally underused feature of CodeIgniter, and it deserves some promotion. So here it is. Check it out.

And that's all for now. Come back real soon!

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Fark
  • Furl
  • YahooMyWeb

15 Responses to “Getting Started With CodeIgniter: Part 5 - Loose Ends”

  1. Fred Says:

    Thanks! This was a great set of tutorials. I’m attempting to make the transition from css/ui guy to programmer and this helped a lot.

  2. amitava Says:

    Thanks! great tutorial.. Please do cover some advanced topics such as authentication, AJAX etc.

  3. Andrei Says:

    I think the correct entries in index.php:

    $system_folder = “system”;
    $application_folder = “../application”;

  4. Mike Says:

    @Andrei:

    That would only work of your system folder is in the same directory as index.php. In my case, I move it above the web root, so you have to tell it to look there instead.

  5. Andrei Says:

    Mike.

    Thanks for the clarification.
    By the way, the tutorial is very helpfull.

  6. Lee Says:

    Mike - Where would be a good place to store php ‘include’ files? In with the application, or with the public_html directory…

  7. Mike Says:

    @Lee

    If you’re talking about a header, footer, navbar, stuff like that, the best idea is to make them each their own view. That way, in the controller, you can do something like:

    $this->load->view(’header’);
    $this->load->view(’your_content_view’);
    $this->load->view(’footer’);

    You could get away with including actual php files via the include() function (the web root folder is probably the best place for them) but it kind of goes against the whole philosophy of CI.

    Thanks for reading!

  8. Sika Says:

    Wow, you sure do know how to explain things. Thank U, keep up the good work!

  9. Bernd Says:

    Thank you very much. I enjoyed your tutorial and your writing style. Ever thought about writing a book about your experiences? Great!

  10. Mike Says:

    @Bernd

    Ha! Thanks for the flattery, but no. You would be the only reader!

  11. Bernd Says:

    ;-)

  12. Conceptric — Blog Archive » Code ignition Says:

    […] configuration files it all worked perfectly. The reasons for doing this sort of thing have been documented elsewhere, and I agreed with them from this security standpoint, however this structure also fits better with […]

  13. bozboz Says:

    I would just like to thank you for a great set of tutorials. I have been trying to get my head round MVC / CI and these have really helped. Although CI has one of the best sets of documentation I have ever come across, it’s always good to have a perspective from a real world user.

    As others have suggested - maybe you should think about writing a book!

    Many thanks.

  14. Tom Says:

    Finally; a series of CI tutorials which aren’t just a rehash of the user guide. I got to part 2 and was 30px from asking for a case study to help those of us who still hadn’t grasped the site structure side of it all, but come part 5, you delivered.

    If by any chance you are not sure what CI aspect to write about next, a tut on CI+mod_rewrite* would go down sweet - especially by someone who writes as well as you do.

    *Something I’m having problems with at the moment; I can’t get my head around RewriteRules/Conds, so I’ve been using those supplied by various CI articles on mod_rewrite. I’m not sure how to arrange it so that index.php is dropped, but I can still reference the functions in my default controller via URLs.
    eg. domain.com/index.php/content_serve_controller/blog -> domain.com/blog

    (I don’t think default controllers are visible in the URL, but I think that example demonstrates what I mean). Any help would be appreciated.

    Many thanks!

  15. Mike Says:

    @Tom

    Good idea. I’ll try and put together a tutorial on .htaccess and routes.php. Did you ever sort out the problem you were having?

Leave a Reply