Creating A Microsite Manager With CodeIgniter
Creating A Microsite Manager With CodeIgniter
Contents
Introducing CodeIgniter
Whats Model-View-Controller? Why Bother with MVC?
2
3 4
5
6 6 7 8
Getting Started
The Login Area Creating the Template View Creating the Login Form Reworking the index() Function Creating the MAdmins Model Creating the verifyUser() Function Autoloading the MAdmins Model A Small Note about Creating Your First User
10
11 12 14 15 16 17 17 18
18
19 22 35
39 40
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
These requirements address the what (or the content) in the microsite, but eventually, the microsite needsto be published to a target location. The developers may have little or no control over the target environment. They may or may not, for example, be able to specify a type of database or even PHP support. In fact, they may be publishing to an ASP or ColdFusion server, or to a server that only supports basic HTML. For these reasons, the microsite manager you build needs a publication function that extracts information from the microsite database tables, applies templates to it, and then publishes the material to a designated target, all as flat HTML. Once you have all of the material in HTML (with supporting assets and media files, of course), youre free to place that information on any web server you choose.
Introducing CodeIgniter
CodeIgniter was created by 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. Ive been able to create prototype applications within hours of talking to a client, and then refined the prototypes over the course of a fewdays. Its this kind of prototyping power and flexibility, by the way, that will transform the way you work with clients but more on that later. Unlike Ruby on Rails, CodeIgniter doesnt require you to adhere to a strict set of coding rules. For example, you dont have to name your database tables a certain way and your models another. You dont 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: There is a growing toolbox of helpers and libraries that help you do your job quickly. You dont have to learn a complex templating language. You dont need to work with large-scale monolithic libraries. You can run your applications in PHP 4 or PHP 5 without too much hassle. CodeIgniter applications run with exceptional performance.
I wont get into too many more details right now. Youll start seeing the difference once you start coding. For now, though, it might be useful to talk a little bit about MVC, and why its important. Then you can get to work.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Whats Model-View-Controller?
Model-View-Controller is a design pattern that allows developers to separate their code cleanly into three categories: Models help you maintain data. Views display data from the model and user interface elements. Controllers handle user events that interact with models and views.
The important thing to remember is that MVC takes the user into account it begins with them. Its the user who clicks a link, moves the mouse, or submits a form. Its the controller that monitors this activity and takes the appropriate action (such as manipulating the model and updating the view). Because of MVCs 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 you to track eCommerce items in an online store: You would have a model for product information. You would have multiple views to show single products, products in a list, products in search results, and so on. You would have 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. 2. 3. 4. 5. 6. 7.
The user visits the stores 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 models data is then transmitted to the view for the home page. The view (including the data retrieved by the model) is what the user sees in the browser. The user clicks on a link to see details on a particular product. 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. The cycle begins anew when the user takes another action, such as running a search or clicking on a link.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
user
displayed for interacts with
view
controller
updates
manipulates
model
Figure 1: The Model-View-Controller framework inaction.
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, its possible, some might argue, to create an MVC application without a model, or to gang-press view code into the controller. Its not a good idea, but it can be done. For right now, our simple analogy will hold.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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. Its true that changing the model in some way (retrieving 15 products instead of 10) will change the view, but the developer didnt have to dig through her view (or controller) 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.
Figure 2: CodeIgniter.com.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
In other words, the most important folders in /system/application are: controllers/, models/, and views/. If youll spend 99 percent of your time inside this folder, youll spend 99 percent of that time with models, views, and controllers that you build.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
config.php
The 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 applications 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/;
Once youve 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. Many CodeIgniter developers prefer to keep this value blank.
$config[index_page] = ;
To make this work, you need to include an .htaccess file to the CodeIgniter root directory. For now, keep the value as index.php. After youve set this option value, theres 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;
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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 someopportunities to talk about configuration options, and Ill bring up some points if its appropriate.
database.php
The 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, anddatabase driver. Each of these is stored in the $db array under the default group, which means you could have numerous connection groups, each with it 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 youve set the $active_group variable correctly, your application will stay connected.
$active_record = TRUE; $active_group = default; $db[default][hostname] $db[default][username] $db[default][password] $db[default][database] $db[default][dbdriver] $db[default][dbprefix] $db[default][pconnect] $db[default][db_debug] $db[default][cache_on] $db[default][cachedir] $db[default][char_set] $db[default][dbcollat] = = = = = = = = = = = = your-host-name; your-db_username; your-db_password; your-db_name; mysql; ; TRUE; TRUE; FALSE; ; utf8; utf8_general_ci;
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
There is one more task to be done before leaving the autoload file. I am talking about 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 any more you can autoload them and use the model functions at any point. Although you dont have any models built yet, at various points in this application, youll be building models and then immediately autoloading them in the autoload.php file.
You will translate these requirements into CodeIgniter terms. Ninety-nine percent of this application will be some kind of administrative dashboard that will be password-protected. The other one percent will be a combination of a login screen and whatever the system outputs to the target destination. Ironically, it is this very last part, the output HTML, that everyone will think of as the application, but it is really only exported data. You need to build two sets of controllers for CodeIgniter. The first set of controllers, which you will call Welcome, contains a single view, the login screen. The second group contains multiple controllers, one for the main dashboard and the others for pages, uploads, categories/folders, and users. This second set of controllers will be organized under a folder called admin/ within your controllers directory. There is more about this below in this Wrox Blox, but for now, just know that you can organize your files into convenient folders.
10
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Please 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 class Welcome in the welcome.php file. Furthermore, you need a constructor of the same name inside your class. The example above is PHP 4.I. If you were working in PHP 5, your constructor would look as follows:
<?php class Welcome extends Controller { function __construct(){ parent::Controller(); session_start(); } }//end controller class ?>
Notice that in both examples, Im initializing PHP Sessions with session_start(). Youll see why Im using PHP Sessions, as you continue working with the application. CodeIgniter comes with its own
11
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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 youre doing here is making the $data array available to a view called template. The template array (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 will contain 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 our first very simple index() function of the Welcome controller, the login template will contain a very simple form.
12
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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 series of CSS and JavaScript files that all live under an includes/ folder and various subdirectories under that. CodeIgniter doesnt 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 archive. This 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=wrapper> <div id=header> <?php $this->load->view(nav);?> </div> <div id=main> <?php $this->load->view($main);?> </div> <div id=footer> Copyright 2008 Your-Company-Here </div> </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 (as you did with nav), and at other times, you can dynamically load a view with a PHP variable. Notice that youre doing just that by feeding in the variable $main in the second instance.
13
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Youll notice that Im not using the standard HTML form markup here. Instead, Im using CodeIgniters built-in Form helper. This helper contains various shorthand functions that do a lot of heavy lifting foryou. 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 welcome/index, which means you will need to modify your controller function a bit. 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(), ahandy shortcut for your labels (which are good to have on your forms from an accessibility perspective). 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, youll wonder how you got along without this helper.
14
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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 youre 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 havent 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 (youll be building that shortly, as well). If you dont get back a data array, you simply redirect the user to the login form so that they can try to log in again. So heres what you need to do before youre done with the login area:
1. 2. 3.
Create the MAdmins model. Create the verifyUser() function inside that model. Autoload the MAdmins model for future ease of use.
15
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
1. 2. 3.
They must have a name that doesnt 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.
I tend to call my models MSomething because the M stands for model. You may choose whatever naming convention works for you. While youre at it, you need to create the database table that goes with this model. If this were Ruby on Rails or another MVC framework, you would need to name your model after your table, but with CodeIgniter there is no such restriction. Create a table called ms_admins with the following schema:
CREATE TABLE ms_admins ( 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 DEFAULT CHARSET=utf8;
If youre used to creating database tables in MySQL, then nothing about this should surprise you. The tables fields allow you to store a username, e-mail, status, and password, and has an auto-incremented key field called ID.
16
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Notice that youre not exactly using standard SQL queries here to extract the data you want. Although CodeIgniter allows you to use SQL queries, most experienced CodeIgniter developers use the built-in Active Record class and its helper functions. For example, $this->db->select() accepts a list of comma-separated fields, which gets placed intheSELECT part of the query. $this->db->where() accepts two arguments (a field name and avalue)that get put into the WHERE part of the query. You are allowed to add as many calls to $this->db->where() as you want, as they are concatenated with AND [you can change this behavior by using $this->db->or_where()]. You can limit how many records are retrieved by using $this->db->limit(), telling it to run a query with $this->db->get(), and passing in a table name. Then, all you have to do is check whether you get anything back using num_rows(). Finally, return the row with the row_array() command. If you dont get anything, you return an empty array. If you recall, the controller index() 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 will cause the controller to redirect back to the login page.
From now on, you can access the model and its functions without manually loading it.
17
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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.
Along the way, youll create models (and in one case, youll expand what youve done with the MAdmins model) and views to support what you need. Because of time and space constraints, I dont go into extraordinary detail on each part of the application, but you will have enough information that you can easily duplicate the finished application. Youll also have access to all the code in order to create your own microsite manager. Please note that there is no way I can take you through every nook and cranny of this application in the short space allowed. I will give you a detailed view of a few areas and then gloss over the other areas where repeating wont help comprehension. Rest assured that once youve built one set of models, views, and controllers in an administrative dashboard, its very easy to repeat the process whenever you need more screens.
18
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
The controller starts typically enough, with the right naming conventions, and includes a very shortcheck 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. Youre 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; $data[tinymce] = ; $this->load->vars($data); $this->load->view(dashboard); }
Youre doing essentially the same thing you did before, on the login screen, except for two tiny variants: Youre setting a blank value for tinymce (this is a WYSIWYG editor youll talk about that when you build the pages controller). Youre loading a dashboard view instead of the template view.
19
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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/pages/, pages);?></li> <li><?php echo anchor(admin/uploads/, files);?></li>
20
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Essentially, this is the main navigation that will go across the top of the admin dashboard. Once youve 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. Whats so great about the anchor() function? It automatically adds the base URL to any internal links so you dont have to keep track of it. This one little benefit will keep you coming back to the anchor() tag over and over again. Heres the admin_footer view:
Copyright © <?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, heres the admin_home view:
<ul> <li><b><?php echo anchor(admin/categories/,Manage Categories);?>.</b></li> <li><b><?php echo anchor(admin/pages/,Manage Pages);?>.</b></li> <li><b><?php echo anchor(admin/uploads/,Manage Files);?>.</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> <?php echo form_open(admin/dashboard/build_site); echo form_submit(submit, build site now!); echo form_close(); ?>
It is basically the same list of links seen in the main navigation, but with a form added to the end. Theform is very basic, consisting of a single button that says, build site now! The form posts to the build_site() function of the Dashboard controller. Before you move on to the other controllers, finish the Dashboard controller. You still need the logout() and build_site() functions. Heres 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); }
21
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Now that youve got the dashboard figured out, create the other controllers you need, starting with the Admin area first.
All of our administrative controllers will follow this basic pattern. Following 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:
<?php class 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 will require the creation of a model function called getAllUsers(). As you can guess, this function will retrieve 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); }
22
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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 doesnt, it loads the admin_admins_ editview. Notice that it also runs the getUser() model function, which youll use to populate the form fields.
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, theres 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); } } ?>
23
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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(ms_admins); 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 => $_POST[username], email => $_POST[email], status => $_POST[status], password => md5($_POST[password]) ); $this->db->insert(ms_admins,$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 properly.
function updateUser(){ $data = array(username => $_POST[username], email => $_POST[email], status => $_POST[status],
24
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
The deleteUser() function accepts an ID, and then sets the status of that record to inactive. Im not a big believer in actually deleting items from the database, which is why Ive opted for a deactivation instead of deletion. Because of that, youre using $this->db->update() instead of $this->db->delete().
function deleteUser($id){ $data = array(status => inactive); $this->db->where(id, $id); $this->db->update(ms_admins, $data); }
25
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Figure 4: User home page. The admin_admins_create view is just a simple form. It should allow the user to enter a username, password, and other information.
<h1><?php echo $title;?></h1> <?php echo form_open(admin/admins/create); echo form_label(username,u); $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 youve 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 manually set, or it can be generated from a query. For all intents and purposes, the admin_admins_edit view contains the same exact form, except youre loading values into each field. Remember that the controller function edit() has run the getUser()
26
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Categories
First, lets 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, youll 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 that youre calling different views.
27
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
28
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
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, youre building administrative panels, so the view wont vary much. Theyll either be a listing of available records, or a form that allows you to create new records or edit existing records. Heres the model for categories, called MCats:
<?php class MCats extends Model{ function MCats(){ parent::Model(); } function getCategory($id){ $data = array(); $options = array(id => $id); $Q = $this->db->getwhere(ms_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(ms_categories); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data; } function addCategory(){ $data = array( name => str_replace( , _,$_POST[name]), shortdesc => $_POST[shortdesc], longdesc => $_POST[longdesc], status => $_POST[status], sortorder => $_POST[sortorder],
29
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
30
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Pages
The Pages controller and model (MPages) are essentially identical to Categories, except that the schema related to pages has a few more fields. I wont go into all the detail of the controller and model (as you can investigate yourself using the code), but heres the schema for ms_pages:
CREATE TABLE ms_pages ( id int(11) NOT NULL auto_increment, category_id int(11) NOT NULL default 0, name varchar(255) NOT NULL default , localname varchar(255) NOT NULL default , title varchar(255) NOT NULL, keywords varchar(255) NOT NULL default , description varchar(255) NOT NULL default , path varchar(255) NOT NULL default , content text character set utf8 collate utf8_unicode_ci NOT NULL, sidebar text character set utf8 collate utf8_unicode_ci NOT NULL, shownav enum(yes,no) NOT NULL default yes, pageorder int(3) NOT NULL default 0, status enum(active,inactive) NOT NULL default active, PRIMARY KEY (id) ) ENGINE=MyISAM DEFAULT CHARSET=uft8;
Notice that there are fields for the page name, title, keywords, description, and content, which you would expect, but also other fields. For example, the localname field allows you to put in an alternative name that shows up in navigation. Ive used it to good effect when I had to create translations or show navigation links in other languages. The shownav field tells the application whether to show this page in the navigation at all. The sidebar field can hold HTML content for a sidebar area. One other thing you should note about the Pages area is that you will want to install a WYSIWYG editor. In the code, youll see that Ive installed TinyMCE, then placed the configuration options for it inside my Pages controller so that I can pass it all into my views.
class Pages extends Controller { function Pages(){ parent::Controller(); session_start(); if ($_SESSION[userid] < 1){ redirect(welcome/index,refresh); } $this->tinyMce = <!-- TinyMCE --> <script type=text/javascript src= . base_url().includes/tiny_mce/tiny_mce.js></script> <script type=text/javascript> tinyMCE.init({
31
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Because you pass this value into the appropriate functions [in this case, the create() and edit() functions of the Pages controller], you end up with WYSIWYG editors where you want them (i.e., the text areas devoted to content and sidebar data).
function create(){ if ($this->input->post(name)){ $this->MPages->addPage(); redirect(admin/pages/index,refresh); }else{ $data[title] = Create Page; $data[main] = admin_pages_create; $data[tinymce] = $this->tinyMce; $cats = $this->MCats->getCategoriesNav(); $data[categories] = $this->_flatten_cats($cats); $this->load->vars($data); $this->load->view(dashboard); } } function edit($id=0){ if ($this->input->post(name)){ $this->MPages->updatePage(); redirect(admin/pages/index,refresh); }else{ $data[title] = Edit Page; $data[main] = admin_pages_edit; $data[page] = $this->MPages->getPage($id); $data[tinymce] = $this->tinyMce; $cats = $this->MCats->getCategoriesNav(); $data[categories] = $this->_flatten_cats($cats); $this->load->vars($data); $this->load->view(dashboard); } }
Did you notice the use of a special function called $this->_flatten_cats()? In CodeIgniter, any controller function that begins with an underscore (_) is automatically treated as a private function. Auser cant enter the name of that function as a destination. In this special case, the _flatten_cats() function accepts a list of categories, and then flattens it into a more human-readable format. Specifically, it makes a list of categories look like a directory tree. This will be used in any category dropdowns on page create/edit forms, making it that much easier to associate a page with a category.
32
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Uploads
The uploads area is very similar to the pages and categories. Before I talk about where this controller differs (e.g., how you upload a file with CodeIgniter), I want to show you the schema for the ms_files database table:
CREATE TABLE ms_files ( id int(11) NOT NULL auto_increment, name varchar(255) NOT NULL default , keywords varchar(255) NOT NULL default , path varchar(255) NOT NULL default , status enum(active,inactive) NOT NULL default active, PRIMARY KEY (id) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
The goal is to be able to upload individual files and store some information about them in the ms_files table, but then to store the files in a specific area of the site. At this point, Ive set aside the /includes/ uploads/ folder as my repository for any uploaded files. In the next section, I talk about the site-building function and all the things youll have to do to make the publication process work. CodeIgniter makes file uploads work seamlessly. Lets walk through the file creation process, starting with the view, then working our way through to the controller, and then the model. Our file creation view is called admin_uploads_create, and its just a simple form:
<h1><?php echo $title;?></h1> <?php echo form_open_multipart(admin/uploads/create); echo form_label(file name,fname); $data = array(name=>name,id=>fname,size=>25); echo form_input($data) .</p>; echo form_label(keywords,short);$data = array(name=>keywords,id=>short,size=>40);
33
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Its important to note that youre using form_open_multipart() to open the form; that way, the form is ready to accept file uploads. Also notice that youve used the form_upload() shortcut to create the file upload widget in the form. Heres the specific controller function that deals with file uploads:
function create(){ if ($this->input->post(name)){ $this->MUploads->addFile(); redirect(admin/uploads/index,refresh); }else{ $data[title] = Upoad File; $data[main] = admin_uploads_create; $data[tinymce] = ; $this->load->vars($data); $this->load->view(dashboard); } }
So far, nothing surprising, right? Take a look at that addFile() function in the MUploads model. The first thing you do is prepare the $data array, as you normally would:
function addFile(){ $data = array( name => $_POST[name], keywords => $_POST[keywords], status => $_POST[status] );
Next, check for a value in $_FILES, which is the superglobal associated with file uploads. If there is a value associated with $_FILES[myfile], then set the CodeIgniter $config parameters. These parameters allow you to control the path, allowed file types, maximum upload size, and more.
34
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Once you have the $config array squared away, load the upload directory using the $config array as the second argument:
$this->load->library(upload, $config);
Run the do_upload() command, checking for errors as you go (and exiting immediately if you run into problems):
if(!$this->upload->do_upload(myfile)){ echo $this->upload->display_errors(); exit(); } $U = $this->upload->data();
If the upload is successful, you will end up with a file_name key in your upload array. If you find that, just make sure your $data[path] value is set to that, as that will be written to your database upon insertion. Youre done!
if ($U[file_name]){ $data[path] = $U[file_name]; } } $this->db->insert(ms_files, $data); }
Make sure that your target directory (in this case, /includes/uploads) is writable.
1. 2.
Some way to extract all the information from the database in an orderly fashion (e.g., grouped by category). A set of rules that will transform page records into flat HTML files.
35
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
First, set up a folder called stage_assets/ in the includes/ folder. You can place any assets for the microsite in there. For example, in many projects, there is an images/ folder and some CSS files. All of those go into the stage_assets/ folder. Next, create a series of template views (Ive called mine public_home, public_inner, etc.) that you store in the /system/application/views/ folder. These views represent the look and feel of your completed site design. Again, these have nothing to do with your manager views. They should include places for keywords, title, content, and sidebar (all the fields you designated in your ms_pages table). Next, you can create a file called MY_url_helper.php in the /system/application/helpers/ folder. By creating a file with this name, CodeIgniter will know that you are seeking to extend the default URL helper. What you want to do is create various functions that will help you keep track of paths. Youll use these functions in the site-building function. Heres what you can put in your helper extension file:
<?php function prepend_url(){ return /; } function cms_prep(){ return /var/www/html/whatever/; } function target_prep(){ return /var/www/html/target/; } function target_url(){ return http://www.example.com/target-whatever/; } ?>
Finally, lets consider the build_site() function in the Dashboard controller. Its a bit complicated, but once you go through it step-by-step, youll see that its very straightforward.
36
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Next, you make sure that you have items in the $pages and $cats arrays and start processing the stack. The first step is to delete everything in the target area (dont worry, this will more than likely be a staging server!) to make sure that anything you deactivate in the manager doesnt keep showing up over on the target area. Next, rsync everything from your stage_assets/ folder to the target area:
if (count($pages) && count($cats)){ unset($cats[0]); //DELETE TARGET AREA shell_exec(rm -rf . target_prep().*); //COPY OVER ASSETS shell_exec(rsync -avz .cms_prep().includes/stage_assets/ . target_prep());
Next you loop through all the categories, creating a folder for each one. If you have a category called contact_us, this process will create a folder with that name. At the same time, create a folder named files to hold the uploaded files:
//NOW YOU MAY CREATE NEW CATS! foreach ($cats as $id => $path){ @mkdir(staging_prep().$path); } @mkdir(target_prep().files);
Next, loop through all the pages, making sure that you add .html to any page name that doesnt already have it on the end:
foreach ($pages as $page){ if (!preg_match(/\.html$/,$page[path])){ $page[path] .= .html; }
Figure out which template you need to use (either public_home or public_inner). The project, with whichI was involved, had radically different designs for these two types of pages, and indeed, withyour project, you might have very different designs for each category (e.g., a different look for contact pages vs. products pages).
37
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Once you know what $final looks like, you need to figure out where it belongs in the site hierarchy. Essentially, any page with a category_id of 0 belongs in the site root; otherwise, it really belongs in some other folder.
//2. determine path! if ($page[category_id] == 0){ $finalpath = target_prep().$page[path]; }else{ $finalpath = target_prep(). $cats[$page[category_id]] . / . $page[path]; }
Once you figure out where it goes, use the write_file() function to write the file to the right directory. The write_file() function comes to us by way of the File helper and simplifies the task of writing a file to the filesystem:
//3. write to staging folder if (!write_file($finalpath,$final)){ die(cant write to $finalpath!); } }
Once youre done looping through all the pages, loop through the files array and copy them over to the files/ folder you created earlier. Finally, redirect the user to the Admin dashboard after setting a quick Session variable to indicate that files are now ready for viewing:
//dont forget uploaded files! if (count($files)){ foreach ($files as $F){ $file = $F[path]; @copy(cms_prep().includes/uploads/$file, target_prep().files/$file); } } $_SESSION[target_ready] = true; redirect(admin/dashboard,refresh); }else{ redirect(admin/dashboard,refresh); } }
38
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Conclusion
Once the process runs, youll see several folders and files copied into your target directory. In Figure 5, my target directory is the microsite_stage directory off the server root. Theres a folder for every category, an images folder, a CSS file, and various other HTML files present.
Figure 5: Results of the process. By now, what you have is a compact, portable microsite manager that exports all of your database data (and associated files) as static pages and folders in a designated spot. This designated area can be a staging server with files that can later be transferred, via FTP or rsync, to a live server. This arrangement gives your marketing team a lot of flexibility. They can create content for their microsite, design views, upload files, and organize content into virtual folders; then, when theyre ready, they can build a site and see what everything looks like. If they need to fix something, they can do that quickly and easily, and then build their site again.
39
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
40
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.
odeIgniter is lighting up the PHP development space, 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 reusing existing code instead of writing it from scratch; although similar to Ruby on Rails, CodeIgniter is popular as a way to build Rails-like code without learning a new programming language Walks readers through the steps of building several types of applications with CodeIgniter, including blogs, forums, and content management; also provides problem-solving techniques and tips on everyday issues not typically covered in reference manuals for programmers Covers a range of topics helpful to developers of all stripes, from novice programmers to code gurus; topics include an overview of agile methodologies and approaches, the MVC approach, helpers and libraries, model and schema for products, and Ajax and Scriptaculous.
Professional CodeIgnitert
By THOMAS MYER 978-0-470-28245-8 Paper 304 pages
Visit us at www.wrox.com
Wrox Blox0 Creating a Microsite Manager with CodeIgniter By Myer - ISBN0 97804704133711 Prepared for CHRISTOPHER RINGWALD/ email0 [email protected] Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written permission 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.