Comp4711 – Internet Development CodeIgniter Cookbook Comp4711 #2 – Sept 14, 2011.
-
Upload
franklin-marshall -
Category
Documents
-
view
220 -
download
3
Transcript of Comp4711 – Internet Development CodeIgniter Cookbook Comp4711 #2 – Sept 14, 2011.
Comp4711 – Internet Development
CodeIgniter Cookbook
Comp4711
#2 – Sept 14, 2011
Comp4711 – Internet Development W4L1 JSP Introduction
CodeIgniter Cookbook
1) Infrastructure2) Development vs Deployment3) Fixing the URL4) Models5) Controllers6) Authentication7) Views8) Templates9) Helpers10) Libraries11) Error Handling
Comp4711 – Internet Development W1L1 XML Introduction
1. Infrastructure
• Goals: – Reduce complexity of webapp (not inc CI)– Reuse CI across webapps (only 1 copy)– Improve security (not accessible)
• Solution:– Move CI folder up 1 or 2 levels (outside of
htdocs)– Keep application folder inside webapp– Fix configuration in index.php– Move assets out of webapp folder
1. index.php
• $system_folder = "system";
• $system_folder = "../CI";
• Note: Some hosting companies make it awkward to reference outside htdocs
• Note: above assumes webapp is a subfolder of htdocs
• Note: might have to use something likerealpath($_SERVER['DOCUMENT_ROOT']."/../..");
• $application_folder = "application";
• $application_folder = "./application";
• Net result: application is a folder directly under webapp root
2. Development vs Production
• Goals:– Accommodate different passwords &
folder structures for different environments
– Facilitate deployment without mods• Solution:
– $config[][]– Test server name
2.1 config/config.php
• $config['base_url'] = "http://www.galianogulfisland.com/";
• //JLP Adjust for development environment• //NOTE Still have to set port properly in
NetBeans project properties (run configuration)
• if ($_SERVER['SERVER_NAME'] == "localhost") {
• $config['base_url'] = "http://".$_SERVER['HTTP_HOST']."/cq-v3/";
• }
2.2 config/database.php
• $active_group = "default";• $active_record = TRUE;
• $db['default']['hostname'] = "localhost";• $db['default']['username'] = "root";• $db['default']['password'] = "";• $db['default']['database'] = "heritage";• $db['prod']['hostname'] = "www.yada.com";• $db['prod']['username'] = "master";• $db['prod']['password'] = "secret";• $db['prod']['database'] = "ourg_5149";
Comp4711 – Internet Development
3. Fixing the URL
• Goal:– Make the URL short & friendly
• Solutions:– mod_rewrite inside .htaccess– config/routing.php
Comp4711 – Internet Development
3.1 .htaccess sample
• DirectoryIndex index.php index.html• RewriteEngine on• # Allow requests for valid file or folder names,
or some that should be• RewriteCond %{REQUEST_FILENAME} -f [OR]• RewriteCond %{REQUEST_FILENAME} -d [OR]• RewriteCond $1 ^(robots\.txt|favicon\.ico|
style\.css)• RewriteRule ^(.*)$ - [L]• # Change any JSP requests into PHP ones• RewriteRule ^(.*)\.jsp$ ./index.php/$1 [L]• # use index.php as front controller ...• RewriteRule ^(.*)$ ./index.php/welcome/$1 [L]
Comp4711 – Internet Development
3.2 .htaccess
• DirectoryIndex index.php index.html• RewriteEngine on• # Allow requests for valid file or folder names,
or some that should be• RewriteCond %{REQUEST_FILENAME} -f [OR]• RewriteCond %{REQUEST_FILENAME} -d [OR]• RewriteCond $1 ^(robots\.txt|favicon\.ico|
style\.css)• RewriteRule ^(.*)$ - [L]• #• # use index.php as front controller ...• RewriteRule ^(.*)$ ./index.php/$1 [L]
Comp4711 – Internet Development
3.3 config/config.php
• $config['base_url'] = "http://www.galianogulfisland.com/";
• OR set RewriteBase in .htaccess• $config['index_page'] = "";
Comp4711 – Internet Development
3.4 config/routes.php
• $route['default_controller'] = "welcome";• $route['blog/joe'] = "blogs/users/34";• $route['products/([a-z]+)/(\d+)'] =
"$1/id_$2";
Comp4711 – Internet Development
4. Models
• Goal:– Make life easier
• Solution:– Understand Active Record pattern– MY_Model for RDB– MY_Model2 …– Others
Comp4711 – Internet Development
4.1 Active Record Pattern
• Active record is an approach to accessing data in a database.
• A database table or view is wrapped into a class.
• The interface to such an object would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.
• Normal: updates happen automatically; CI: use database class
Comp4711 – Internet Development
4.2 core/MY_Model
• (or models/my_model.php & autoload)
• class MyModel extends Model {
• var $_tableName; // Which table is this a model for a row of?
• var $_keyField; // name of the primary key field
• var $_data; // placeholder for retrieved values
• …• create()• get($key)• add($record)• update()• delete($key)• Exists()
Comp4711 – Internet Development
4.3 models/MyModel2
• class MyModel2 extends MyModel {• var $_keyField2; // second part of
composite primary key• …• get($key1,$key2)• getSome($key)
Comp4711 – Internet Development
4.4 models/Properties
• class Properties extends Model {
• // Fields• var $_data = array(); // Container for the
data from persistent storage (the database).• var $_tableName; // name of the DB
table holding the data• var $_keyField; // name of the primary
key field• var $_valueField; // name of the data
field• …• loadtable(...)• get($key)• put($key,$value)• remove($key)
Comp4711 – Internet Development
4.5 XML models!
• Same/similar API to “conventional” model• Intent is to arrive at bridge/adapters
• $64 question: use SimpleXmlModel, domain model classes, or associative arrays??
Comp4711 – Internet Development
5. Controllers
• Goals:– Routing– Templating– Modular MVC– Business logic in controller– Business logic in model
• Solution:– MY_Controller– Strategies...
Comp4711 – Internet Development
5.1 Single welcome.php
• Welcome extends Controller{• Function index() {…}• Function page2() {…}• Function page3() {...}
Comp4711 – Internet Development
5.2 Multiple controllers
• Welcome extends Controller...• Page1 extends Controller...• Page2 extends Controller...
Comp4711 – Internet Development
5.3 Form gen/handling
• Form handling class?
Comp4711 – Internet Development
5.4 core/MY_Controller.php
• class Application extends CI_Controller {
• // Constructor - establish session variables
• function Application() {• parent::Controller();• // make sure we play the game nicely• $this->load->helper('common');• $this->load->helper('url');• }
• // No restrictions for the front-end• function restrict($roleNeeded=null) {
• }• }
Comp4711 – Internet Development
6. Authentication
• Goal:– Restrict access to parts of site
• Solution:– Role-based authentication– Hooks– Custom controller
Comp4711 – Internet Development
6.1 Authentication package
• // Restrict the current page to a specific role or to a set of roles
• function restrict($roleNeeded=null) {• if ($roleNeeded != null) {• // handle the case of a set of allowed roles• if (is_array($roleNeeded) ) {• if (!in_array($this->gicc->userRole,
$roleNeeded)) {• // Not authorized. Redirect to home page• redirect("/");• exit;• }• }• else• // handle the case of a single applicable role• if ($this->gicc->userRole != $roleNeeded) {• // Not authorized. Redirect to home page• redirect("/");• exit;• }• }• }
Comp4711 – Internet Development
7. Views
• Goals:– Easy page assembly
• Solutions:– Page template– Page components– Business logic in view?
Comp4711 – Internet Development
7.1 template.php
<html> <head> <?php $this->load->view('_meta'); ?> </head> <body class='asd'> <div class='header'> <?php $this->load->view('header'); ?> </div> <div class='body'> <?php $this->load->view($bodypage); ?> </div> </body></html>
Comp4711 – Internet Development
7.2 _xxx.php
• _meta.phpCSS style sheets, metadata, titles, etc
• _header.phpsite-wide header, perhaps with banner
• _sidebar.phpsite-wide navigation
• _footer.phpcopyright, contact, text navbar
Comp4711 – Internet Development
8. Templates
• Goals:– Page consistency– Page pre-processing
• Solutions:– Template package
Comp4711 – Internet Development
8.1 template package
Template parser class?
$data['bulkbody'] = $bulkbody;$data['bulkfrom'] = $bulkfrom;$data['bulkopening'] = $bulkopening;...// let's generate the letter now$this->load->library('parser'); // get the template
helper$preview = "";$choices = $_SESSION['openings'];$template = "templates/opening_".
$choices[$bulkopening];$preview .= $this->parser->parse($template,$data,true);
// apply template, capture output$template = "templates/bulk_mailout";$preview .= $this->parser->parse($template,$data,true);
// apply template, capture output
Comp4711 – Internet Development
8.2 “view template” pattern
View/template.php
Includes views _meta, _header, _footer, _navbar and $body
Set “body” parameter and$this->load->view(“template”,$body);
Comp4711 – Internet Development
9. Helpers
• Goals:– Reuse common code
• Solutions:– Helpers– Be careful of naming conventions
Comp4711 – Internet Development
9.1 Example: common_helper
• Form field handling, using associative array as data transfer object/buffer
• fieldExtract($source,$target,$fields)– $source – assoc array from form– $target – corresponding object– $fields – names of fields in this form
• fieldInject($source,$target,$fields)– $source – original data object– $target – assoc array for parameters to
view– $fields – names of fields in this form
Comp4711 – Internet Development
10. Libraries
• Goals:– Encapsulate useful things
• Solutions:– Libraries– MY_ controller or MY_model go in
application/core
– Object models … libraries? Or models?
Comp4711 – Internet Development
10.1 Example: GICC
• Libraries/GICC.php• Used to hold “global” constants & app
config data• Just one way to do this
Comp4711 – Internet Development
10.2 Example: Product
• Libraries/product.php• Use for object model for entities stored in
an XML document• “models/products” would be the
aggregation of these• Again, just one way to do this
• Will revisit this at half-way point
Comp4711 – Internet Development
11. Error Handling
Goals:• Determine what went wrong
Solutions:• index.php … error_reporting(E_ALL);• application/errors/...• UhOh extension to override CI error
handling with better description & backtrace
• routing/htaccess for common problems