Creating a Blogging Tool With CodeIgniter

43
Thomas Myer Creating a Blogging Tool with CodeIgniter ® Updates, source code, and Wrox technical support at www.wrox.com Wiley Publishing, Inc.

Transcript of Creating a Blogging Tool With CodeIgniter

Page 1: Creating a Blogging Tool With CodeIgniter

Thomas Myer

Creating a Blogging Tool with Codeigniter®

Updates, source code, and Wrox technical support at www.wrox.com

Wiley Publishing, Inc.

Page 2: Creating a Blogging Tool With CodeIgniter

Contents

Introducing CodeIgniter 2What’s Model-View-Controller? 2Why Bother with MVC? 4

Installing and Configuring CodeIgniter 5The Root Folder 6The system/Folder 7The system/application Folder 7Tweaking the Configuration 8

Getting Started 10The Public-Facing Site 12Creating the Template View 14Creating the Home Page View 16Creating the Category View 19Creating the Blog Details View 20Creating the Login Form 22Verifying Logins 23Creating the MAdmins Model 24Creating the verifyUser() Function 24A Small Note about Creating Your First User 25

Creating the Admin Dashboard 25Creating the Dashboard Controller 26Building the Admin Area 28Creating the Rest of the Admin Functions 34

Summary 38About Thomas Myer 39

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 3: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter

Let’s imagine for a second that you’re working on a team of marketers, writers, and designers, and that the marketing manager requests that you create a blogging tool from scratch. It doesn’t have to be complex, but it can’t be any of the off-the-shelf applications available for free on the Web (like WordPress). It has to be small, efficient, and very fast. Most important, it needs to integrate seam-lessly with an existing web site.

Oh, and one more thing: “Could we have a working prototype up and running by 5 p.m. today?” You look at your watch and notice that it is 11:25 a.m. You do a quick calculation — you have just enough time to grab lunch and start cracking away at the project with CodeIgniter. No problem, you think. A blog is pretty simple. You’ve seen hundreds (if not thousands) of them in action, and you’ve integrated all kinds of code with various models. With CodeIgniter by your side, you should be able to kick out most of what you need in just a few hours.

You say yes, you’ll build it, as long as everyone understands that it’s a working prototype. With that, you run off to get some lunch and sketch out some basic requirements.

Sound impossible? With CodeIgniter, it isn’t. In this Wrox Blox, you’ll see how to put together a very simple blogging application in an afternoon. The key here is “simple.” At the end of the process, you won’t have some kind of WordPress competitor. But you will have a very useful, portable, and slick little blogging tool that you can add to any existing site (CodeIgniter or not).

Here’s a quick run down of what you’ll end up with:

q A public-facing home page that shows the last 10 blog posts

q A way to show posts by category

q A way to display a single post with comments (and a way for others to comment on a post)

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 4: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

q An administrative area that requires a username and password for access

q An administrative area to manage users, posts, and categories

Now that you know what to build, it’s time to download CodeIgniter and get the general overview.

Introducing CodeIgniterCodeIgniter was created by the good folks over at EllisLab, Inc. It is a Model-View-Controller (MVC) framework with a very small footprint. In form and function, it is very similar to other MVC frameworks, like Ruby on Rails. Like Ruby on Rails, it requires very little configuration to get started. I’ve been able to create prototype applications within hours of talking to a client, and then refined the prototypes over the course of a few days.

It’s this kind of prototyping power and flexibility, by the way, that will transform the way you work with clients. It allows you to be responsive and collaborative in ways that you’re probably not used to.

Unlike Ruby on Rails, CodeIgniter doesn’t require you to adhere to a strict set of coding rules. For example, you don’t have to name your database tables a certain way, and your models another. You don’t even have to have strictly formatted table fields — which makes CodeIgniter an excellent platform for recoding legacy applications.

Below are a few more great things about CodeIgniter:

q There is a growing toolbox of helpers and libraries that help you do your job quickly.

q You don’t have to learn a complex templating language.

q You don’t need to work with large-scale monolithic libraries.

q You can run your applications in PHP 4 or PHP 5 without too much hassle.

q CodeIgniter applications run with exceptional performance.

This section doesn’t get into too many more details right now. You’ll start seeing the difference once you start coding. For now, it might be useful to talk a little bit about MVC and why it’s important. Then you’ll get to work.

What’s Model-View-Controller?Model-View-Controller is a design pattern that allows developers to separate their code cleanly into three categories:

q Models — help you maintain data.

q Views — display data from the model and user interface elements.

q Controllers — handle user events that interact with models and views.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 5: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

The important thing to remember is that MVC takes the user into account — it begins with them. It’s the user who clicks a link, moves the mouse, or submits a form. It’s the controller that monitors this activity and takes the appropriate action (such as manipulating the model and updating the view).

Because of MVC’s three-part separation, developers can create multiple views and controllers for any given model without forcing changes in the model design. Similarly, multiple controllers can make use of any model. This separation allows for easily maintained, portable, and organized applications. For example, think about an MVC application that allows us to track eCommerce items in an online store. You would have the following:

q A model for product information

q Multiple views to show single products, products in a list, products in search results, and so on

q At least one controller that would organize those views into destinations, such as index() (for home page), product_detail(), and search_results()

Drilling down further, an MVC eCommerce application might involve the following flow of events:

1. The user visits the store’s home page.

�. This simple event requires a controller action for the home page, which makes a quick call to the model to retrieve the 10 most popular products based on recent sales.

�. The model’s data are then transmitted to the view for the home page.

4. The view (including the data retrieved by the model) is what the user sees in the browser.

5. The user clicks a link to see details on a particular product.

6. The underlying controller captures this user input (clicking the link), uses the model to retrieve the product in question from the database, and then loads the appropriate view.

7. The cycle begins anew when the user takes another action, such as running a search or clicking a link.

Another way of thinking about this breakdown of roles is to map it out as follows (see Figure 1):

q User Input and Traffic Control = Controller

q Data Interaction and Processing = Model

q Output = View

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 6: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

4

This three-part analogy is a much simpler way of looking at things. Some might argue that the approach is much too simple. After all, it’s possible, some might argue, to create an MVC application without a model, or to gang-press view code into the controller. It’s not a good idea, but it can be done. For right now, the simple analogy will hold.

Why Bother with MVC?Although at first glance the MVC approach seems like a lot of work, it really isn’t. When the developer of the hypothetical MVC eCommerce application wants to change something about the home page, she asks herself about the nature of the change. Doing so allows her to zero in on the part of the application on which she needs to work. If the developer wants to:

q Change the number of products that get retrieved (or even the order in which the products are displayed), she updates the model.

q Change the way the home page looks, she updates the view.

q Add a new page to the application, she first adds a method to the controller and then builds out any supporting views (to display content in the browser) and models (to gather data from a database).

displayed for interacts with

updates manipulates

user

controllerview

model

Figure 1: The Model-View-Controller framework in action.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 7: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

5

The beauty of the entire system lies in the fact that none of those hypothetical actions on any given part of the MVC triumvirate affects the others. It’s true that changing the model in some way (retrieving 15 products instead of 10) will change the view, but the developer didn’t have to dig through three views (or controllers) to make that change, then later discover another SQL call embedded in other files that did the same thing. Theoretically, on large projects, you could have developers who focus only on Views, Controllers, or Models, thus keeping clean lines of sight on deliverables and responsibilities.

Installing and Configuring CodeIgniterTo get your hands on CodeIgniter, point your browser to www.codeigniter.com and click the Download CodeIgniter button, as illustrated in Figure 2.

Figure �: CodeIgniter.com.

Once you’ve downloaded the Zip archive, double-click it to open it, and place the contents of the archive in your favorite work area. Once you’ve done that, take a moment to tour CodeIgniter.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 8: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

6

Figure �: CodeIgniter’s folder structure.

As you will see, CodeIgniter has a certain folder structure (shown in Figure 3) that looks a bit daunting at first, but believe me, you’ll become very familiar with it.

The Root FolderThe root folder contains an index.php file (called the front controller — it basically routes traffic into the rest of the application), a system/ folder, and a user_guide/ folder. I won’t cover the user_guide/ folder, as it is merely a local copy of the online user guide found at www.codeigniter.com/user_guide/. If you want to explore the documentation, you can do so at your leisure.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 9: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

7

The system/FolderThe system/folder is where all the action happens. This folder contains all the CodeIgniter code of consequence, organized into various folders:

Folder Description

application Contains the application you’re building, which includes your Models, Views, Controllers, and other code (like helpers and class extensions). In other words, this folder is where you’ll do 99% of your work.

cache Contains all cached pages for your application.

codeigniter Where CodeIgniter’s core classes live. You have almost no reason to go in here. All of your work occurs in the application folder.

database Contains core database drivers and other database utilities. Again, there’s no good reason for you to be in this folder.

fonts Contains font-related information and utilities. Again, there’s no reason to spend any time here.

helpers Contains standard CodeIgniter helpers (such as Date, Cookie, and URL helpers). You’ll make frequent use of helpers in your CodeIgniter career, and can even extend helpers thanks to improvements introduced in CodeIgniter version 1.6.

language Contains language files. You can ignore it for now.

libraries Contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard libraries, but those are saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries.

logs The folder to which CodeIgniter writes error and other logs. This needs to be writable if you enable logging.

plugins Contains plug-ins. Plug-ins and helpers are very similar, in that they both allow developers to address an issue or create content (like forms, links, etc.) quickly. The main difference between them is that plug-ins usually consist of one function, while helpers often have many functions bundled inside them.

The system/application FolderThe most important folder, the one that deserves most of your attention, is the /system/application folder (and all of its subfolders). Ninety-nine percent of your work will be done right in this folder, so it deserves your attention. Learning what goes where now will reduce confusion later.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 10: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

The system/application folder is broken down into several folders as shown in the following table:

Folder Description

config Contains several important files that control your configuration options. There are files that manage your database setup and other variables that CodeIgniter needs to know (such as the base URL, which libraries and helpers to autoload, etc.). The four most important files in this folder are config.php, database.php, autoload.php, and routes.php.

controllers Contains the controllers you create for your application.

errors Comes with standard CodeIgniter error templates for 404 pages, PHP errors, and others. You are free to modify these templates to make them fit the look and feel of your application.

hooks Contains any hooks you create for your application. Hooks are the best way to extend the CodeIgniter core safely.

libraries Contains custom libraries you create for your application.

models Contains the models you create for your application.

views Contains the views you create for your application.

In other words, the most important folders in the /system/application folder are controllers/, models/, and views/. You’ll spend practically all your development time working with the Models, Views, and Controllers that you build.

The other very important folder is config/, which contains various important configuration files. You’ll want to open them in an editor for tweaking before starting any project. Most of the time, when you start a new CodeIgniter project, you’ll start with the config/ folder.

Tweaking the ConfigurationThe two most important files in the /system/application/config folder are config.php and database.php. Whenever you start a new CodeIgniter project, the first two files you’ll want to work with are these.

config.phpThe config.php file contains a series of configuration options (all of them stored in a PHP array called, appropriately enough, $config) that CodeIgniter uses to keep track of your application’s information and settings.

The first configuration option you need to set inside of config.php is the base URL of your application. You do that by setting the absolute URL (including the http:// part) for $config[‘base_url’], like so:

$config[‘base_url’] = “http://www.example.com/test/”;

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 11: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

Once you’ve set this configuration option, you can recall it whenever you want using the CodeIgniter base_url() function (a very handy thing to know). This one feature keeps you from having to rewrite hard-coded URLs in your application when you migrate from development to test or from test to production.

The second thing you need to do is set a value for your home page by editing the $config[‘index_page’] configuration option. CodeIgniter ships with a value of “index.php” for this option, which means that index.php will appear in all of your URLs.

After you’ve set this option value, there’s very little to do. For now, leave all the other values at their default settings:

$config[‘uri_protocol’] = “AUTO”;$config[‘url_suffix’] = “”;$config[‘language’] = “english”;$config[‘charset’] = “UTF-8”;$config[‘enable_hooks’] = FALSE; $config[‘subclass_prefix’] = ‘MY_’;$config[‘permitted_uri_chars’] = ‘a-z 0-9~%.:_-’;$config[‘enable_query_strings’] = FALSE;$config[‘controller_trigger’] = ‘c’;$config[‘function_trigger’] = ‘m’;$config[‘log_threshold’] = 0;$config[‘log_ path’] = ‘’;$config[‘log_date_format’] = ‘Y-m-d H:i:s’;$config[‘cache_ path’] = ‘’;$config[‘encryption_key’] = “enter_a_32_character_string_here”;$config[‘sess_cookie_name’] = ‘ci_session’;$config[‘sess_expiration’] = 7200;$config[‘sess_encrypt_cookie’] = TRUE;$config[‘sess_use_database’] = FALSE;$config[‘sess_table_name’] = ‘ci_sessions’;$config[‘sess_match_ip’] = FALSE;$config[‘sess_match_useragent’] = TRUE;$config[‘cookie_prefix’] = “”;$config[‘cookie_domain’] = “”;$config[‘cookie_path’] = “/”;$config[‘global_xss_filtering’] = TRUE;$config[‘compress_output’] = FALSE;$config[‘time_reference’] = ‘local’;$config[‘rewrite_short_tags’] = FALSE

For more details on each of these configuration options, simply read the comments embedded in /system/application/config/config.php. As you progress through the installation, there will be some opportunities to talk about configuration options, and this Wrox Blox will bring up some points if it’s appropriate.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 12: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

10

database.phpThe database.php file contains all the information required to connect to a database. Currently, CodeIgniter supports mysql, mysqli, postgres, odbc, and mssql connections. To connect to your database, simply enter valid information for your hostname, username, password, database name, and database driver.

Each of these is stored in the $db array under the “default” group, which means you could have numerous connection groups, each with their own unique name. For example, you could have one set of connection variables for your development environment and another for your production environment. As long as you’ve set the $active_group variable correctly, your application will stay connected.

$active_record = TRUE;$active_group = “default”;

$db[‘default’][‘hostname’] = “your-host-name”;$db[‘default’][‘username’] = “your-db_username”;$db[‘default’][‘password’] = “your-db_password”;$db[‘default’][‘database’] = “your-db_name”;$db[‘default’][‘dbdriver’] = “mysql”;$db[‘default’][‘dbprefix’] = “”;$db[‘default’][‘pconnect’] = TRUE;$db[‘default’][‘db_debug’] = TRUE;$db[‘default’][‘cache_on’] = FALSE;$db[‘default’][‘cachedir’] = “”;$db[‘default’][‘char_set’] = “utf8”;$db[‘default’][‘dbcollat’] = “utf8_general_ci”;

Other FilesThere are other important files in the config/ directory, namely, routes.php and autoload.php. You don’t need to know anything about routes.php right now, but you will want to autoload a few helpers and libraries before you get started.

You’ll want to autoload the Database and Session libraries, so that you don’t have to call those libraries every time you want to query the database or work with CodeIgniter sessions. On the helpers side, you’ll be using the URL, Form, and Text helpers constantly, so they might as well be loaded.

$autoload[‘libraries’] = array(‘database’,’session’);$autoload[‘helper’] = array(‘url’,’form’,’text’,’typography’);

There is one more task to be done before leaving the autoload.php file: autoloading models. In the days prior to CodeIgniter 1.6, you had to load a model manually every time you used it in your controller. Not anymore! You can autoload them and use the model functions at any point.

Although you don’t have any models built yet, at various points in this application, you’ll be building models and then immediately autoloading them in the autoload.php file.

Getting Star tedNow that CodeIgniter is installed and configured, you’re ready to begin. Take a quick look at the requirements list before you get too deep. The list includes the following:

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 13: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

11

q A public-facing home page that shows the last 10 blog posts

q A way to show posts by category

q A way to display a single post with comments (and a way for others to comment on a post)

q An administrative area that requires a username and password for access

q An administrative area that allows for management of users, posts, and categories

You will translate these requirements into CodeIgniter terms. Eighty percent of this application will be some kind of administrative dashboard that will be password-protected. The other 20 percent is a series of public-facing display pages that contain blog posts. You will need to build two sets of controllers for CodeIgniter:

q The first set, which you will call Blog, will contain a handful of functions.

q The second group contains multiple controllers, one for the main dashboard and the others for posts, categories, and users. This set of controllers will be organized under a folder called admin/ in your controllers directory. There will be more about this later, but for now, just know that you can organize your files into convenient folders.

You will need one model for each database table. Because you will need to track users, posts, categories, and comments, you need a model for each of those. For the time being, you also need database tables for each of these models. You will build those database tables as you go.

Here are the database tables you need. First, the categories table:

CREATE TABLE `categories` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) NOT NULL default ‘’, `shortdesc` varchar(255) NOT NULL default ‘’, `longdesc` text NOT NULL, `status` enum(‘active’,’inactive’) NOT NULL default ‘active’, `sortorder` int(3) NOT NULL default ‘0’, `parentid` int(11) NOT NULL default ‘0’, PRIMARY KEY (`id`)) ENGINE=MyISAM;

Next comes the posts table:

CREATE TABLE `posts` ( `id` int(11) NOT NULL auto_increment, `title` varchar(255) collate utf8_unicode_ci NOT NULL, `tags` varchar(255) collate utf8_unicode_ci NOT NULL, `status` enum(‘draft’,’published’) collate utf8_unicode_ci NOT NULL, `body` text collate utf8_unicode_ci NOT NULL, `category_id` int(11) NOT NULL, `pubdate` datetime NOT NULL, `user_id` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM;

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 14: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

1�

Next, the comments table:

CREATE TABLE `comments` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) collate utf8_unicode_ci NOT NULL, `email` varchar(255) collate utf8_unicode_ci NOT NULL, `body` varchar(255) collate utf8_unicode_ci NOT NULL, `post_id` int(11) NOT NULL, `pubdate` datetime NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM;

And finally, the users table:

CREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `username` varchar(16) NOT NULL default ‘’, `email` varchar(255) NOT NULL default ‘’, `status` enum(‘active’,’inactive’) NOT NULL default ‘active’, `password` varchar(128) NOT NULL default ‘’, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`,`email`)) ENGINE=MyISAM;

You will also have about a dozen views. Most of them will be for our administrative views, but a few will be used on the public-facing side of the web application.

Now that you have all of that roughed in, let’s create the first controller next.

The Public-Facing SiteThe first thing you’re going to build is the public area. This is where users go when they want to read blog posts. You will need some kind of home page, a category home page, a post view page, and some way to log in to the administrative dashboard. Follow these steps:

1. Create the controller. Simply create a welcome.php file in /system/applications/controllers/ and put the following basic information in it:

<?php class Blog extends Controller { function Blog(){ parent::Controller(); session_start(); }}//end controller class

?>

�. Note that when you create a controller, you have to follow a few basic rules. The name of the class is always capitalized, and it must match the name of the file. Therefore, you have the class Blog in the blog.php file. Furthermore, you need a constructor of the same name inside your class. The example above is PHP 4. If you were working in PHP 5, your constructor would look as follows:

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 15: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

1�

<?php class Blog extends Controller { function __construct(){ parent::Controller(); session_start(); } }//end controller class ?>

Notice that in both examples, you’re initializing PHP Sessions with session_start(). You’ll see why you’re using PHP Sessions as you continue working with the application. CodeIgniter comes with its own Sessions, but those are cookie-based and therefore accessible to the client. They can be encrypted, of course, but this fact doesn’t mean that you should completely trust them. Later on, when you build the part of the application that allows users to log in to the administrative panels, you want a more secure system of determining successful login than a client-side cookie. PHP Sessions offers that, as the data are stored server-side.

�. Once you have your constructor in place, all you have to do is add some functions. You will need functions for every single destination in the controller. In this case, you will need a destination for the home page, traditionally handled by an index() function.

Here are the basic functions that we want in our controller:

function index(){ //home page code here} function category(){ //category page code here} function post(){ //post detail page code here}

Your index() function is very basic — it just needs to display some navigation items and a certain number of blog posts. This content isn’t placed in the controller function, but is instead handled in a view, which you’ll get to below. As you can see, we are using some models to call up data for the view to display:

function index(){ $data[‘posts’] = array(); //we will replace soon! $data[‘cats’] = array(); //we will replace soon! $data[‘title’] = “Welcome”; $data[‘main’] = ‘public_home’; $this->load->vars($data); $this->load->view(‘template’); }

Notice that you are saving information in a $data array (like the variables: title and main), and then loading that array with $this->load->vars($data). All you’re doing here is making the $data array available to a view called Template.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 16: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

14

The Template view (which will be saved in the /system/application/views folder as the template.php file) is going to be a generic template that you can use throughout the administrative dashboard. The template contains a hole in the center of it (a PHP doughnut, if you will) in which you can include whatever other template you want. In this case, whatever value is saved in $data[’main’] will be used to call up the template that fills that hole.

In the case of the first very simple index() function of the Blog controller, the public_home template will contain the results of some data you’re going to pull out of the database. For now, you want to keep that data manual. You’ll hook it up to your model later.

Creating the Template ViewBefore building that form, let’s create the template.php file. This example uses one of the default templates from Dreamweaver CS3 just for speed.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”><html xmlns=”http://www.w3.org/1999/xhtml”><head><meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8” /><title><?php echo $title; ?></title><link href=”<?php echo base_url();?>includes/css/main.css” rel=”stylesheet” type=”text/css” /><script type=”text/javascript”>//<![CDATA[base_url = ‘<?php echo base_url();?>’;//]]></script><!--[if IE 5]><style type=”text/css”> /* place css box model fixes for IE 5* in this conditional comment */.twoColFixLtHdr #sidebar1 { width: 230px; }</style><![endif]--><!--[if IE]><style type=”text/css”> /* place css fixes for all versions of IE in this conditional comment */.twoColFixLtHdr #sidebar1 { padding-top: 30px; }.twoColFixLtHdr #mainContent { zoom: 1; }/* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */</style><![endif]--></head>

<body class=”twoColFixLtHdr”>

<div id=”container”> <div id=”header”> <h1><?php echo $title;?></h1> <!-- end #header --></div> <div id=”sidebar1”>

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 17: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

15

<?php $this->load->view(‘nav’); ?> <!-- end #sidebar1 --></div> <div id=”mainContent”> <?php $this->load->view($main);?> <!-- end #mainContent --></div> <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats --><br class=”clearfloat” /> <div id=”footer”> <p>Copyright 2008 Your Company Inc | <?php echo anchor(‘blog/login’, ‘admin’);?></p> <!-- end #footer --></div><!-- end #container --></div></body></html>

Remember to save this file in the /system/application/views/ folder!

This template.php file is very simple, but you need to look at a few things before you go any further. First, please notice that it refers to a CSS file that lives under an includes/ folder and various subdirectories under that. CodeIgniter doesn’t come with a designated storage place for all the images, CSS files, JavaScript files, and other goodies that you need to build a web application. The best thing to do with these assets is to create a folder off the root (at the same level as the system/ folder) and store everything in there, out of the way.

All of the files you will need, by the way, are included in the zip file that you download with this Wrox Blox. This zip file includes all the files referred to under the top-level includes/ folder.

The other thing you should notice is the sections marked $this->load->view(). They are reprinted in the following example:

<div id=”container”> <div id=”header”> <h1><?php echo $title;?></h1> <!-- end #header --></div> <div id=”sidebar1”> <?php $this->load->view(‘nav’); ?> <!-- end #sidebar1 --></div> <div id=”mainContent”> <?php $this->load->view($main);?><!-- end #mainContent --></div>

You can nest your views using the $this->load->view() command, as long as you feed it the name of a view in your application. Sometimes you manually set the name of a view (like you did with nav), and at other times, you can dynamically load a view with a PHP variable. Notice that you’re doing just that by feeding in the variable $main in the second instance.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 18: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

16

Why $main? Wasn’t the variable called $data[’main’] in the controller? Yes, but once $data is loaded into the view, you access the values by using the keys of that array. This makes it pretty handy when you’re trying to remember what to access. It also makes it possible to pass all manner of data arrays into a view without any trouble at all.

In this case, the $main stands for “main content.” You could use another semantically valid name, like $content or $fill_in_the_donut_hole, but you get the idea. You now have a template you can use for any non-logged-in view you may need.

Creating the Home Page ViewSo now you know that you need a home page view called public_home. That’s what the controller is going to load. Specifically, you need to grab some data and then feed them to the view. For now, you have an empty array for the posts and another empty array for the navigation. This is good enough for you to get started.

As soon as you have the views nailed down, you can go back and create your models. First, let’s tackle the side navigation. All you want is a link back to the home page and a link to each category. Here’s what the nav view would look like:

<?php echo anchor(“blog/index”,”home”);?><br/> <h3>Categories</h3><?phpif (count($cats)){ foreach ($cats as $id => $name){ echo anchor(“blog/category/$id”,$name).”<br/>”; }}?>

As you can see, all you need is for $data[‘cats’] in your Blog controller to contain a simple array. The keys of this array would be category IDs, and the values would be category names. Keep that in mind while you work on the public_home template view.

The public_home view is very simple. It’s basically expecting an array from the Blog controller. If it finds one, it iterates over the array and prints out the title of the blog posting and the first 200 words.

<?phpif (count($posts)){ foreach ($posts as $key => $list){ echo “<h2>”.$list[‘title’].”</h2>\n”; echo auto_typography(word_limiter($list[‘body’], 200)); echo anchor(‘blog/post/’.$list[‘id’],’read more >>’); } echo “<br/><br/>”;} ?>

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 19: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

17

Notice the use of the auto_typography() and word_limiter() functions. These are both examples of CodeIgniter helpers. To use them, you have to make sure that you’ve autoloaded them, or load the helpers right before you do call them. To autoload, make the appropriate entries in the system/application/config/autoload.php file. See the “Other Files” section above in this Wrox Blox as a reference. Luckily, they have been autoloaded, so you’re free to move on to your models.

Also notice that you’re not displaying the full blog posts here on this view, but providing a link to another page that shows details. More on this in a bit.

Models in CodeIgniter allow you to maintain a relationship with a data source. Most of the time, that data source is a database table, but it could be a text file, cookie, session, or anything else for that matter. At the moment, you need two basic models. The first allows you to talk to the categories table, and the second allows you to talk to the posts table.

All models follow the same set of rules:

1. They must have a name that doesn’t conflict with a controller.

�. The name of the class is usually capitalized and matches the file name.

�. They live in the /system/application/models/ directory.

You should call the categories model MCats, and the posts model MPosts. Other developers have their own naming conventions, preferring to use model_x or x_model for their model names, but the simple Mx model is short and tells you right away that you’re dealing with a model. As you work with this application, you’ll be adding plenty of functions to each model, but for now, all you need is a few functions to get you going.

In the MCats model, you need an easy way to pull out a simple array of categories so you can build a navigation element on the public-facing web site. Before you build that, you need to create a model:

<?phpclass MCats extends Model{ function MCats(){ parent::Model(); }}//end class?>

So far, so good, right? Just like with controllers, your model name must be identical to its filename, and you have to instantiate the model as you would any other PHP class.

Before you do anything, remember to add your models to the autoload.php file (might as well add the one for users, posts, and comments while you’re at it!):

$autoload[‘model’] = array(‘MCats’,’MPosts’,’MAdmins’,’MComments’);

Now that they’re autoloaded, you’re free to use functions from them without having to call them beforehand.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 20: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

1�

Next, create a function called getTopCategories(). This function will retrieve all the top-level categories from the categories table:

function getTopCategories(){ $this->db->where(‘parentid’,0); $Q = $this->db->get(‘categories’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[$row[‘id’]] = $row[‘name’]; } } $Q->free_result(); return $data; }

Now all you have to do is go back to our Blog controller and insert this function into the right space:

function index(){ $data[‘posts’] = array(); $data[‘cats’] = $this->MCats->getTopCategories(); $data[‘title’] = “Welcome”; $data[‘main’] = ‘public_home’; $this->load->vars($data); $this->load->view(‘template’); }

Next, you need a simple function that will retrieve a certain number of posts for the home page. You don’t want to hardcode the number of posts in the model function, so you’ll pass in a limit. Here’s what the model function would look like:

<?php

class MPosts extends Model{

function MPosts(){ parent::Model(); }

function getLivePosts($limit){ $data = array(); $this->db->limit($limit); $this->db->where(‘status’, ‘published’); $this->db->order_by(‘pubdate’,’desc’); $Q = $this->db->get(‘posts’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data; }}?>

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 21: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

1�

Notice that we’re using the passed-in $limit variable to limit how many records we retrieve. We’re further limiting ourselves to just published posts (using the where() function) and ordering the result set by pubdate descending. Now we’re free to go back and add this function into the Blog controller, stipulating that we want 10 posts:

function index(){ $data[‘posts’] = $this->MPosts->getLivePosts(10); $data[‘cats’] = $this->MCats->getTopCategories(); $data[‘title’] = “Welcome”; $data[‘main’] = ‘public_home’; $this->load->vars($data); $this->load->view(‘template’); }

Creating the Category ViewYou now need a similar approach to a category page. In other words, if a visitor clicks a category in the side navigation (like “news” or “rants”), they should end up on a destination page that shows them all the posts assigned to that category.

In your Blog controller, you’d have a category() function:

function category($id){ $data[‘category’] = $this->MCats->getCategory($id); $data[‘posts’] = $this->MPosts->getAllPostsByCategory($id); $data[‘cats’] = $this->MCats->getTopCategories(); $data[‘title’] = $data[‘category’][‘name’]; $data[‘main’] = ‘public_home’; $this->load->vars($data); $this->load->view(‘template’); }

It’s very similar to the index() function. It assumes that we’re going to pass in some kind of category ID (which we will refer to as simply $id in this context). It then uses that $id to fetch the category via a getCategory() function, and all posts assigned to a category via a getAllPostsByCategory() function.

First, let’s build the getCategory() function in the MCats model:

function getCategory($id){ $data = array(); $this->db->where(‘id’,$id); $this->db->limit(1); $Q = $this->db->get(‘categories’); if ($Q->num_rows() > 0){ $data = $Q->row_array(); } $Q->free_result(); return $data; }

This function is very simple. It retrieves one record from the categories table that matches the ID you pass in, returning an array.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 22: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�0

Here’s the getAllPostsByCategory() function of the MPosts model:

function getAllPostsByCategory($catid){ $data = array(); $this->db->where(“category_id”,$catid); $this->db->where(‘status’, ‘published’); $Q = $this->db->get(‘posts’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data; }

You pass in a $catid and use it to filter which posts you return, making sure that you also only grab those posts with a status of “published.” Make sure that you return an array, because in the end, you’re passing all of this information to the public_home view, which you’ve already used for your home page.

Creating the Blog Details ViewAt some point, you need to show an individual blog posting (and any comments that have been made about that posting). In the controller, a function called post() has been set aside. Let’s revisit that now:

function post($id){ $data[‘post’] = $this->MPosts->getPost($id); $data[‘comments’] = $this->MComments->getComments($id); $data[‘cats’] = $this->MCats->getTopCategories(); $data[‘title’] = $data[‘post’][‘title’]; $data[‘main’] = ‘public_post’; $this->load->vars($data); $this->load->view(‘template’); }

You’re passing in an $id variable that will map to the post ID. You’ll use that here in much the same way you used the category ID when you viewed posts by category. It looks like you need to add one more function to the MPosts model [getPost()] and create a model called MComments.

Let’s add the getPost() function to the MPosts model first:

function getPost($id){ $data = array(); $this->db->where(‘id’,$id); $this->db->limit(1); $Q = $this->db->get(‘posts’); if ($Q->num_rows() > 0){ $data = $Q->row_array(); } $Q->free_result(); return $data; }

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 23: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�1

No surprises here. You pass in an $id and use that to grab one record from the posts table, then return that record as an array.

On to building the MComments model. You need a getComments() function that will retrieve all the comments related to a certain post. You’ll also need an addComment() function, which you’ll be adding below. Let’s build that all out now:

<?php class MComments extends Model{ function MComments(){ parent::Model(); } function getComments($postid){ $data = array(); $this->db->where(‘post_id’,$postid); $Q = $this->db->get(‘comments’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data; }

function addComment(){ $now = date(“Y-m-d H:i:s”); $data = array( ‘name’ => $this->input->post(‘name’), ‘email’ => $this->input->post(‘email’), ‘body’ => strip_tags(substr$this->input->post(‘body’),0,255)), ‘post_id’ => $this->input->post(‘post_id’), ‘pubdate’ => $now ); $this->db->insert(‘comments’, $data); }}?>

Now that you have the models under control, you should create a simple view called public_post. This view will consist of the blog posting and any comments that are associated with it, followed by a simple form that will allow users to post their own comments.

<?phpecho auto_typography($post[‘body’]);?>

<h3>Comments</h3><?phpif (count($comments)){

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 24: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

foreach ($comments as $key => $list){ echo “<b>Comment by “.$list[‘name’].”:</b><br/>\n”; echo auto_typography($list[‘body’]); } echo “<br/>”;}?> <p><b>Add your own comment:</b></p>

<?phpecho form_open(“blog/addcomment”);echo form_label(‘your name’,’name’) .”<br/>”;$data = array(‘name’=>’name’,’id’=>’name’,’size’=>25);echo form_input($data) .”</p>”;

echo form_label(‘your email’,’email’) .”<br/>”;$data = array(‘name’=>’email’,’id’=>’email’,’size’=>25);echo form_input($data) .”</p>”;

echo form_label(‘your comment’,’comment’) .”<br/>”;$data = array(‘name’=>’body’,’id’=>’comment’,’rows’=>5, ‘cols’=>’30’);echo form_textarea($data) .”</p>”;

echo form_hidden(‘post_id’,$post[‘id’]);echo form_submit(‘submit’,’add comment’);echo form_close();?>

Whenever you get the chance, you should let CodeIgniter help you as much as possible (as you’re doing in this Wrox Blox). You’re using auto_typography() to help lay out the content for the posting and comments. You’re also using helpers like form_open(), form_label(), form_input(), form_hidden(), and form_submit() to help you build a very fast and simple comment form.

Notice the form_open() function points to blog/addcomment. This means that you need a new function in your Blog controller, one called addcomment(). This function has a very simple job: insert the comment from the form into the database and then redirect the user back to the blog posting they were on.

The way to do this is very simple: Call the model function you want to do the job. In this case, you want the addComment() function of the MComments model.

function addcomment(){ if ($this->input->post(‘body’)){ $this->MComments->addComment(); } redirect(‘blog/post/’.$this->input->post(‘post_id’), ‘refresh’);}

Creating the Login FormWe now need to discuss a Login form so that blog administrators can get into the dashboard. In the Blog controller, you need to add a login() function:

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 25: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

function login(){ $data[‘cats’] = $this->MCats->getTopCategories(); $data[‘title’] = “Login to the Dashboard”; $data[‘main’] = ‘public_login’; $this->load->vars($data); $this->load->view(‘template’); }

This is simple enough, and the public_login view is even simpler:

<?php$udata = array(‘name’=>’username’,’id’=>’u’,’size’=>15);$pdata = array(‘name’=>’password’,’id’=>’p’,’size’=>15); echo form_open(“blog/verify”);echo form_label(‘username’,’u’) .”<br/>”;echo form_input($udata) . “</p>”;echo form_label(‘password’,’p’) .”<br/>”;echo form_password($pdata) . “</p>”;echo form_submit(‘submit’,’login’);echo form_close();?>

To open a form, use form_open() and pass in the URI to which the form posts. This is equivalent to the action attribute of a form. In your case, you want this simple form to post to blog/verify, which means you will need to add a new function.

Notice that you then use form_input() and form_password() to create a text field followed by a password field. Also notice that each of these has a short array containing necessary values (like the field name, DOM ID, and size) that gets passed to that field. Also notice the use of form_label(), a handy shortcut for your labels (which are a good accessibility thing to have on your forms).

Finally, you create a submit button with form_submit() and close the form with form_close(). Although you may now be wondering why you would go to all this trouble, after only a short while, you’ll wonder how you got along without this helper.

Verifying LoginsAt this point, you have a Login form that posts back to blog/verify, which means that you need to add a verify() function. If there are POST data, the function needs to take the values from the form, encrypt the password using some simple method, and then check to see whether there are any users in the database that match the values from the form. The encrypting and checking can be done inside the model to keep things simple.

Here’s a complete version of the verify() function:

function verify(){ $this->load->library(‘encrypt’); if ($this->input->post(‘username’)){ $u = $this->input->post(‘username’); $pw = $this->input->post(‘password’); $row = $this->MAdmins->verifyUser($u,$pw);

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 26: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�4

if (count($row)){ $_SESSION[‘userid’] = $row[‘id’]; redirect(‘admin/dashboard’,’refresh’); }else{ redirect(blog/login,’refresh’); } }else{ redirect(‘blog/login’,’refresh’); } }

The first thing you do now is load the encrypt library. This library is only used during login, so there is no need to autoload it. Once loaded, it will be used by the model you’re going to create to communicate with the database table that will store administrative users.

The second thing you do is use $this->input->post() to check to see whether there is a value in a field called username. If there is a value, then you grab the username and password values and hand this information off to the MAdmins model (which you haven’t built yet) and specifically, the verifyUser() function of that model.

What you need to receive is an array of data. If you do get back an array, you can populate a PHP session variable called userid and then redirect the user to the admin/dashboard controller (you’ll be building that shortly, as well). If you don’t get back a data array, you simply redirect the user to the Login form so they can try to log in again.

So here’s what you need to do before you’re done with the login area:

1. Create the MAdmins model.

�. Create the verifyUser() function inside that model.

Creating the MAdmins ModelHere is a basic, bare-bones model for MAdmins, stored in madmins.php:

<?php

class MAdmins extends Model{

function MAdmins(){ parent::Model(); }}//end class?>

Creating the verifyUser() FunctionNow that you have the basic MAdmins model in place, you need to create the verifyUser() function. This function will receive two arguments, a username and a password. It needs to encrypt the password before running the query (as you’re only going to save encrypted passwords in the system). It then returns an array of data (whether empty or not) to the calling controller:

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 27: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�5

function verifyUser($u,$pw){ $this->db->select(‘id’); $this->db->where(‘username’,$u); $this->db->where(‘password’, md5($pw)); $this->db->where(‘status’, ‘active’); $this->db->limit(1); $Q = $this->db->get(‘ms_admins’); if ($Q->num_rows() > 0){ $row = $Q->row_array(); return $row; }else{ return array(); }}

If you recall, the controller verify() function that is calling verifyUser() is expecting a row containing an ID, so that it can set a PHP Session value. It will accept an empty array, but that causes the controller to redirect back to the login page.

A Small Note about Creating Your First UserYou’ll notice that you’re only storing encrypted passwords in the database table. Later, you’ll be asked to log in before you can see the admin dashboard, which you won’t be able to do because there is no user in the system!

To get around that little problem, generate your first user by hand, using phpMyAdmin or some other database admin tool. To generate a proper password, use PHP to echo a string wrapped with md5(), then store that string in your database.

For example, <?php echo md5 (‘password’);?>. This should generate an md5 hash of the string password, which, once stored in the database, will allow you to log in with that password.

Creating the Admin DashboardNow that the login area is fully created, you have been introduced to Controllers, Models, and Views and can easily create the rest of the application. The rest of the application will involve building out the administrative dashboard, with separate controllers for categories, pages, files, and users (remember, you need to manage those as well!).

To keep things organized, you’re going to create a folder called admin/ inside the /system/application/controllers/ folder, and you’ll store all your controllers in there. You will need to build the following controllers:

q Dashboard — This is the “home area” for your administrative area, and includes all publication functions.

q Posts — To manage posts.

q Categories — To manage folders or categories in the site.

q Admins — To manage admin users.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 28: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�6

Along the way, you’ll create models (and in one case, you’ll expand what you’ve done with the MAdmins model) and views to support what you need. Because of time and space constraints, this Wrox Blox doesn’t go into great detail on each part of the application, but you will have enough information that you can easily duplicate the finished application. You’ll also have access to all the code in order to create your own microsite manager.

Rest assured that once you’ve built one set of Models, Views, and Controllers in an administrative dashboard, it’s very easy to repeat the process whenever you need more screens.

Creating the Dashboard ControllerThe Dashboard controller needs two very simple functions:

q index() — This contains all the code you need to display the home page of the admin dashboard.

q logout() — Allows users to log out.

Here’s what the top of our Dashboard controller looks like (remember, it is stored in the /system/ application/controllers/admin folder):

<?php

class Dashboard extends Controller { function Dashboard(){ parent::Controller(); session_start(); if ($_SESSION[‘userid’] < 1){ redirect(‘blog/login’,’refresh’); } }

}//end class

The controller starts typically enough, with the right naming conventions, and includes a very short check to make sure that the Session variable called userid has been set. If it has a value less than 1, then the user is redirected to the Welcome controller, and specifically to the Login form. You’re going to add this little bit of code to every single controller in the admin/ folder to keep out any unauthorized users.

Once that little bit of business is done, you can build the index() function:

function index(){ $data[‘title’] = “Dashboard Home”; $data[‘main’] = ‘admin_home’; $this->load->vars($data); $this->load->view(‘dashboard’);}

You’re doing essentially the same thing you did before, on the Login screen, except you’re loading a Dashboard view instead of the Template view.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 29: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�7

The Dashboard view is very simple, and looks like this:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”><html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”><head> <meta http-equiv=”content-type” content=”text/html; charset=utf-8” /> <title><?php echo $title; ?></title><link href=”<?= base_url();?>includes/css/admin.css” rel=”stylesheet” type=”text/css” /><script type=”text/javascript”>//<![CDATA[base_url = ‘<?= base_url();?>’;//]]></script>

<?php echo $tinymce;?>

</head><body><div id=”wrapper”> <div id=”header”> <?php $this->load->view(‘admin_header’);?> </div>

<div id=”main”> <?php $this->load->view($main);?> </div> <div id=”footer”> <?php $this->load->view(‘admin_footer’);?> </div></div></body></html>

This Dashboard template, in turn, loads an admin_header, an admin_footer, and whatever value has been loaded into $data[’main’] from the controller (in this case, admin_home).

Here is the admin_header view:

<div id=’globalnav’><ul><li><?php echo anchor(“admin/dashboard/index”,”home”);?></li><li><?php echo anchor(“admin/categories/”,”categories”);?></li><li><?php echo anchor(“admin/posts/”, “posts”);?></li><li><?php echo anchor(“admin/admins/”, “users”);?></li><li><?php echo anchor(“admin/dashboard/logout/”, “logout”);?></li></ul></div>

Essentially, this is the main navigation tool that goes across the top of the admin dashboard. Once you’ve built all the necessary controllers and views, all of this will start working like a charm. For now, take a look at the use of the anchor() shortcut function. This function is part of the URL helper. It builds links for you, and accepts two arguments, the link destination and the link text.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 30: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

What’s so great about the anchor() function? It automatically adds the base URL to any internal links so you don’t have to keep track of it. This one little benefit will keep you coming back to the anchor() tag over and over again.

Here’s the admin_footer view:

Copyright &#169; <?php echo date(“Y”); ?> Your Company Name

This one line of HTML and PHP will put a copyright notice on the bottom of each page.

Finally, here’s the admin_home view:

<ul><li><b><?php echo anchor(“admin/categories/”,”Manage Categories”);?>.</b></li><li><b><?php echo anchor(“admin/posts/”,”Manage Posts”);?>.</b></li><li><b><?php echo anchor(“admin/admins/”,”Manage Users”);?>.</b></li><li><b><?php echo anchor(“admin/dashboard/logout/”,”Logout”);?>.</b></li></ul>

It is basically the same list of links seen in the main navigation. You could, if you wanted, add more information in there, like a listing of the last five postings made on the blog.

Before you move on to the other controllers, finish the Dashboard controller. You still need the logout() and build_site() functions. Here’s the logout() function, which basically unsets the PHP Session variable userID and redirects the user to the login screen:

function logout(){ unset($_SESSION[‘userid’]); redirect(‘welcome/index’,’refresh’); }

Now that you’ve got the Dashboard figured out, create the other controllers you need, starting with the Admin area first.

Building the Admin AreaThe admin area already has a model (MAdmins), so all you have to do is create a controller that will refer to it, add any other functions you may need, and then build your views.

Creating the Admins ControllerGenerally speaking, you need just three or four main functions within any given admin-type controller to make things work smoothly:

q An index() function allows users to see data within the database table at a glance.

q A create() function allows users to create new data in the table.

q An edit() function allows users to edit existing data in a table.

q A delete() function allows users to remove (or deactivate) data in a table.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 31: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

All of our administrative controllers will follow this basic pattern. The following code is the Admins controller, with each section above inserted into the code. The first part is the header, which should look extremely familiar to you by now:

<?phpclass Admins extends Controller { function Admins(){ parent::Controller(); session_start(); if ($_SESSION[‘userid’] < 1){ redirect(‘welcome/index’,’refresh’); } }

The index() function loads the admin_admins_home view and requires the creation of a model function called getAllUsers(). As you can guess, this function retrieves all users from the database:

function index(){ $data[‘title’] = “Manage Users”; $data[‘main’] = ‘admin_admins_home’; $data[‘admins’] = $this->MAdmins->getAllUsers(); $data[‘tinymce’] = ‘’; $this->load->vars($data); $this->load->view(‘dashboard’); }

The create() function is very simple. You want to create a dual-purpose function here, similar to your login screen. If there are POST data, run a function called addUser() and redirect the user to the index() function. If not, show the admin_admins_create view:

function create(){ $this->load->library(‘encrypt’); if ($this->input->post(‘username’)){ $this->MAdmins->addUser(); redirect(‘admin/admins/index’,’refresh’); }else{ $data[‘title’] = “Create User”; $data[‘main’] = ‘admin_admins_create’; $data[‘tinymce’] = ‘’; $this->load->vars($data); $this->load->view(‘dashboard’); } }

Similarly, the edit() function also looks for POST data. If it finds any, it runs the updateUser() function and redirects the user to the index() function. If it doesn’t, it loads the admin_admins_edit view. Notice that it also runs the getUser() model function, which you’ll use to populate the form fields.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 32: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�0

function edit($id=0){ $this->load->library(‘encrypt’); if ($this->input->post(‘username’)){ $this->MAdmins->updateUser(); redirect(‘admin/admins/index’,’refresh’); }else{ $data[‘title’] = “Edit User”; $data[‘main’] = ‘admin_admins_edit’; $data[‘admin’] = $this->MAdmins->getUser($id); $data[‘tinymce’] = ‘’; $this->load->vars($data); $this->load->view(‘dashboard’); } }

Finally, there’s the delete() function, which will pass in a user ID via a link and run the deleteUser() model function:

function delete($id){ $this->MAdmins->deleteUser($id); redirect(‘admin/admins/index’,’refresh’); }}?>

Expanding the MAdmins ModelYou now have to add several functions to the MAdmins model: getAllUsers(), getUser(), addUser(), updateUser(), and deleteUser(). It’s probably a good idea to work on them now before you start doing anything with the views, which will be simple enough.

The easiest function to understand is getUser(). All you have to do is feed the function an ID and it will return all the data associated with the record:

function getUser($id){ $data = array(); $this->db->where(‘id’,$id); $this->db->limit(1); $Q = $this->db->get(‘users’); if ($Q->num_rows() > 0){ $data = $Q->row_array(); } $Q->free_result(); return $data; }

The getAllUsers() function is similarly easy to understand. It returns all rows in the designated table (in this case, ms_admins):

function getAllUsers(){ $data = array(); $Q = $this->db->get(‘users’);

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 33: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�1

if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data;}

The addUser() function accepts an incoming array of POST data and then uses $this->db->insert() to place those data in the right table:

function addUser(){ $data = array(‘username’ => $this->input->post(‘username’), ‘email’ => $this->input->post(‘email’), ‘status’ => $this->input->post(‘status’), ‘password’ => md5($this->input->post(‘password’)) ); $this->db->insert(‘users’,$data);}

The updateUser() function also accepts an incoming array of POST data and then updates the table using $this->db->update(). Notice that tucked away inside the POST data is some kind of ID field. You should make sure to put that inside the view to keep things working correctly.

function updateUser(){ $data = array(‘username’ => $this->input->post(‘username’), ‘email’ => $ this->input->post(‘email’), ‘status’ => $ this->input->post(‘status’), ‘password’ => md5($this->input->post(‘password’)) ); $this->db->where(‘id’,$ this->input->post(‘id’)); $this->db->update(‘users’,$data);}

The deleteUser() function accepts an ID and then sets the status of that record to “inactive.” I’m not a big believer in actually deleting items from the database, so that’s why I’ve opted for a deactivation instead of deletion. Because of that, you’re using $this->db->update() instead of $this->db->delete():

function deleteUser($id){ $data = array(‘status’ => ‘inactive’); $this->db->where(‘id’, $id); $this->db->update(‘users’, $data);}

Creating the ViewsNow that the Controller and Model functions are in place, all you need to build are the views. You need three views: a main index view, a Create form, and an Edit form. Once you have all three in place, you can tie it all together with the rest of the application to make things work correctly.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 34: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

The admin_admins_home view is just a simple table that displays all the available records from the database table. Remember that the controller calls the model function getAllUsers(), and that function returns an array and saves it in $data[‘admins’]. Therefore, you will need to loop through $admins in the view:

<h1><?php echo $title;?></h1><p><?php echo anchor(“admin/admins/create”, “Create new user”);?>

if (count($admins)){ echo “<table border=’1’ cellspacing=’0’ cellpadding=’3’ width=’400’>\n”; echo “<tr valign=’top’>\n”; echo “<th>ID</th>\n<th>Username</th><th>Status</th><th>Actions</th>\n”; echo “</tr>\n”; foreach ($admins as $key => $list){ echo “<tr valign=’top’>\n”; echo “<td>”.$list[‘id’].”</td>\n”; echo “<td>”.$list[‘username’].”</td>\n”; echo “<td align=’center’>”.$list[‘status’].”</td>\n”; echo “<td align=’center’>”; echo anchor(‘admin/admins/edit/’.$list[‘id’],’edit’); echo “ | “; echo anchor(‘admin/admins/delete/’.$list[‘id’],’delete’); echo “</td>\n”; echo “</tr>\n”; } echo “</table>”;}?>

Notice that you can easily create a new user with the link along the top, and edit or delete any existing record once it loads up in the table. When you’re done, your user area will look a little like the illustra-tion in Figure 4.

Figure 4: User home page.

The admin_admins_create view is just a simple form. It should allow the user to enter a username, pass-word, and other information:

<h1><?php echo $title;?></h1>

<?phpecho form_open(‘admin/admins/create’);echo form_label(“username”,”u”);

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 35: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

$data = array(‘name’=>’username’,’id’=>’uname’,’size’=>25);echo form_input($data) .”</p>”;

echo form_label(“email”,”email”);$data = array(‘name’=>’email’,’id’=>’email’,’size’=>50);echo form_input($data) .”</p>”;

echo form_label(“password”,”pw”);$data = array(‘name’=>’password’,’id’=>’pw’,’size’=>25);echo form_password($data) .”</p>”;

echo form_label(“status”,”status”);$options = array(‘active’ => ‘active’, ‘inactive’ => ‘inactive’);echo form_dropdown(‘status’,$options) .”</p>”;

echo form_submit(‘submit’,’create admin’);echo form_close();?>

Notice that you’ve introduced another element here called form_dropdown(), a handy shortcut that allows the easy creation of dropdowns. All you have to do is create an array of options and then pass it in to form_dropdown() to create your values. This array can be set manually, or it can be generated from a query.

For all intents and purposes, the admin_admins_edit view contains the same exact form, except you’re loading values into each field. Remember that the controller function edit() has run the getUser() model function to pull in the corresponding record for a given user ID. Those data were stored in $data[‘admin’], so you can access them via $admin.

<h1><?php echo $title;?></h1>

<?phpecho form_open(‘admin/admins/create’);echo form_label(“username”,”u”);$data = array(‘name’=>’username’,’id’=>’uname’,’size’=>25, ‘value’=>$admin[‘username’]);echo form_input($data) .”</p>”;

echo form_label(“email”,”email”);$data = array(‘name’=>’email’,’id’=>’email’,’size’=>50, ‘value’=>$admin[‘email’]);echo form_input($data) .”</p>”;

echo form_label(“password”,”pw”);$data = array(‘name’=>’password’,’id’=>’pw’,’size’=>25, ‘value’=>’’);echo form_password($data) .”</p>”;

echo form_label(“status”,”status”);$options = array(‘active’ => ‘active’, ‘inactive’ => ‘inactive’);echo form_dropdown(‘status’,$options,$admin[‘status’]) .”</p>”;

echo form_submit(‘submit’,’update admin’);echo form_close(); ?>

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 36: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�4

Creating the Rest of the Admin FunctionsNow that the Admins controller is in place, it’s time to create Models, Views, and Controllers for categories, pages, and uploads. Each of these controllers follows the exact same pattern you’ve seen with the Admins area, so I won’t spend a lot of time on each section. I especially won’t spend a lot of time on the views, as you can inspect them easily enough when you look at the companion code for this Wrox Blox.

CategoriesFirst, let’s talk about categories. Categories, for the purposes of this application, are defined as generic containers (like folders) that can hold pages. When you create the site building function for the Dashboard controller, you’ll organize all the output into their proper categories, using the category names as folder names.

The categories’ area has a very simple controller. Looking at it, you will notice that almost the same thing is going on in this controller as went on in the Admins controller. The only difference is, you’re calling different views.

Here’s the Categories controller:

<?phpclass Categories extends Controller { function Categories(){ parent::Controller(); session_start();

if ($_SESSION[‘userid’] < 1){ redirect(‘welcome/index’,’refresh’); } } function index(){ $data[‘title’] = “Manage Categories”; $data[‘main’] = ‘admin_cat_home’; $data[‘categories’] = $this->MCats->getAllCategories(); $this->load->vars($data); $this->load->view(‘dashboard’); } function create(){ if ($this->input->post(‘name’)){ $this->MCats->addCategory(); redirect(‘admin/categories/index’,’refresh’); }else{ $data[‘title’] = “Create Category”; $data[‘main’] = ‘admin_cat_create’; $data[‘categories’] = $this->MCats->getTopCategories(); $this->load->vars($data); $this->load->view(‘dashboard’); } } function edit($id=0){

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 37: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�5

if ($this->input->post(‘name’)){ $this->MCats->updateCategory(); redirect(‘admin/categories/index’,’refresh’); }else{ $data[‘title’] = “Edit Category”; $data[‘main’] = ‘admin_cat_edit’; $data[‘category’] = $this->MCats->getCategory($id); $data[‘categories’] = $this->MCats->getTopCategories(); $this->load->vars($data); $this->load->view(‘dashboard’); } } function delete($id){ $this->MCats->deleteCategory($id); redirect(‘admin/categories/index’,’refresh’); }}//end class?>

As you can see, the same patterns emerge. The controller calls model functions, sets variables, and loads those variables into a particular view. In your case, you’re building administrative panels, so the view won’t vary much. They’ll either be a listing of available records or a form that allows you to create new records or edit existing records.

You’ve already created a few functions in the MCats model as you worked on the public side of the site; now it’s time to add a few more, so you can continue working on the admin side:

<?phpclass MCats extends Model{ function MCats(){ parent::Model(); }

function getCategory($id){ $data = array(); $options = array(‘id’ => $id); $Q = $this->db->getwhere(‘categories’,$options,1); if ($Q->num_rows() > 0){ $data = $Q->row_array(); }

$Q->free_result(); return $data; } function getAllCategories(){ $data = array(); $Q = $this->db->get(‘categories’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 38: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�6

$data[] = $row; } } $Q->free_result(); return $data; }

function addCategory(){ $data = array( ‘name’ => str_replace(“ “, “_”,$this->input->post(‘name’)), ‘shortdesc’ => $this->input->post(‘shortdesc’), ‘longdesc’ => $this->input->post(‘longdesc’), ‘status’ => $this->input->post(‘status’), ‘sortorder’ => $this->input->post(‘sortorder’), ‘parentid’ => $this->input->post(‘parentid’) );

$this->db->insert(‘categories’, $data); } function updateCategory(){ $data = array( ‘name’ => str_replace(“ “, “_”,$this->input->post(‘name’)), ‘shortdesc’ => $this->input->post(‘shortdesc’), ‘longdesc’ => $this->input->post(‘longdesc’), ‘status’ => $this->input->post(‘status’), ‘sortorder’ => $this->input->post(‘sortorder’), ‘parentid’ => $this->input->post(‘parentid’) ); $this->db->where(‘id’, $this->input->post(‘id’)); $this->db->update(‘categories’, $data); } function deleteCategory($id){ $data = array(‘status’ => ‘inactive’); $this->db->where(‘id’, $id); $this->db->update(‘categories’, $data); }} function getTopCategories(){ $data[0] = ‘root’; $this->db->where(‘parentid’,0); $Q = $this->db->get(‘categories’); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[$row[‘id’]] = $row[‘name’]; } } $Q->free_result(); return $data; }?>

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 39: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

�7

PostsThe Posts controller and model (MPosts) are essentially identical to Categories, except that the schemata related to pages has a few more fields. I won’t go into all the detail of the Controller and Model (as you can investigate yourself using the code).

Here are the primary functions of the Posts controller:

<?php

class Posts extends Controller { function Posts(){ parent::Controller(); session_start();

if ($_SESSION[‘userid’] < 1){ redirect(‘blog/login’,’refresh’); } } function index(){ $data[‘title’] = “Manage Posts”; $data[‘main’] = ‘admin_posts_home’; $data[‘posts’] = $this->MPosts->getAllPosts(); $data[‘cats’] = $this->MCats->getTopCategories(); $this->load->vars($data); $this->load->view(‘dashboard’); }

function create(){ if ($this->input->post(‘title’)){ $this->MPosts->addPost(); redirect(‘admin/posts/index’,’refresh’); }else{ $data[‘title’] = “Create Post”; $data[‘main’] = ‘admin_posts_create’; $data[‘cats’] = $this->MCats->getCategoriesDropDown(); $this->load->vars($data); $this->load->view(‘dashboard’); } } function edit($id=0){ if ($this->input->post(‘title’)){ $this->MPosts->updatePost(); $this->session->set_flashdata(‘message’,’Post updated’); redirect(‘admin/posts/index’,’refresh’); }else{ //$id = $this->uri->segment(4); $data[‘title’] = “Edit Post”; $data[‘main’] = ‘admin_posts_edit’;

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 40: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

$data[‘post’] = $this->MPosts->getPost($id); $data[‘cats’] = $this->MCats->getCategoriesDropDown(); $this->load->vars($data); $this->load->view(‘dashboard’); } } function delete($id){ $this->MPosts->deletePost($id); $this->session->set_flashdata(‘message’,’Post deleted’); redirect(‘admin/posts/index’,’refresh’);}

}//end class?>

SummaryNow that you have an administrative area up and running, create a few categories and start publishing posts. What you’ll see is a growing list of categories in your navigation and a growing list of Blog posts, as illustrated in Figure 5. It isn’t the prettiest thing in the world, but you’ve met your end of the deal: a working blog application prototype in a matter of hours!

Figure 5: Your Blog home Page.

By now, what you have is a compact, portable blogging application written in CodeIgniter that you can use as a stand-alone publishing tool or integrated blog controller in another CodeIgniter application. It can even be installed in its own subfolder of a non-CodeIgniter site very easily.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 41: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®

��

About Thomas MyerThomas Myer is a technical book author, consultant, and web developer. In 2001, he founded Triple Dog Dare Media in Austin, Texas. Triple Dog Dare Media focuses its attention on helping companies create CodeIgniter-based applications like content management, portals, and eCommerce systems.

Thomas Myer is the author of No Nonsense XML Web Development with PHP (Sitepoint, 2004) and Lead Generation on the Web (O’Reilly, 2007). His new book, Professional CodeIgniter from WROX, hit the bookstores in July 2008. He has also authored dozens of technical and business articles for IBM DeveloperWorks, Amazon Web Services, AOL, Darwin Magazine, and others.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 42: Creating a Blogging Tool With CodeIgniter

Creating a Blogging Tool with Codeigniter®Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana

ISBN: 978-0-470-41338-8

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. CodeIgniter is a registered trademark of EllisLab, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this Wrox Blox.

This PDF should be viewed with Acrobat Reader 6.0 and later, Acrobat Professional 6.0 and later, or Adobe Digital Editions.

Usage Rights for Wiley Wrox Blox. Any Wiley Wrox Blox you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:

• Are entitled to three downloads • Are entitled to make a backup copy of the file for your own use • Are entitled to print the Wrox Blox for your own use• Are entitled to make annotations and comments in the Wrox Blox file for your own use• May not lend, sell or give the Wrox Blox to another user • May not place the Wrox Blox file on a network or any file sharing service for use by anyone other than yourself or

allow anyone other than yourself to access it• May not copy the Wrox Blox file other than as allowed above• May not copy, redistribute, or modify any portion of the Wrox Blox contents in any way without prior permission

from Wiley

If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday – Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States only) or 317-572-3994 (International) 8 a.m. – 8 p.m. EST, Monday - Friday).

Acquisitions Editor DirectorJenny WatsonDevelopment EditorMaureen SpearsTechnical EditorEd FinklerProduction EditorDaniel Scribner

Copy EditorCate CaffreyEditorial ManagerMary Beth Wakefield Production ManagerTim Tate

Vice President and Executive Group PublisherRichard SwadleyVice President and Executive PublisherJoseph B. WikertProofreaderNancy Carrasco

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.

Page 43: Creating a Blogging Tool With CodeIgniter

Ready for more?Build onto the knowledge that you just gained from this Wrox Blox.

Visit us at www.wrox.com

Professional CodeIgniterBy THOMAS MYER

978-0-470-28245-8 • Paper • 304 pages

C odeIgniter is lighting up the PHP developmentspace, and this book shows programmers how to

join the action

• CodeIgniter is an MVC (model-view-controller)framework for PHP that is generating a lot of buzz,because it allows developers to save time by reusingexisting code instead of writing it from scratch; althoughsimilar to Ruby on Rails, CodeIgniter is popular as a wayto build Rails-like code without learning a newprogramming language

• Walks readers through the steps of building severaltypes of applications with CodeIgniter, including blogs,forums, and content management; also providesproblem-solving techniques and tips on everyday issuesnot typically covered in reference manuals forprogrammers

• Covers a range of topics helpful to developers of allstripes, from novice programmers to code gurus; topicsinclude an overview of agile methodologies andapproaches, the MVC approach, helpers and libraries,model and schema for products, and Ajax andScriptaculous

Professional CodeIgniter is available now!

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordancewith the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior writtenpermission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.copyright laws is strictly prohibited.