wiki:How Do I Codeigniter

How Do I Codeigniter?

Here are a couple quicktime videos from their site:

Hello World

10 minute video, does a good job explaining how the framework operates.

Our folder structure will be slightly different; the application folder will not be inside system, but up one level so it is in the same folder as system. Also, don't worry too much about knowing how to do what he's doing in the config folder. Everything we do will be in application.

http://codeigniter.com/tutorials/watch/intro/

Create a blog in 20 minutes

Shows how CI interacts with a MySQL database. As above, folder structure will be slightly different and constructors may also look slightly different. Also, he is using the Scaffolding library in the video; we won't be using that, and has been removed from current version of Codeigniter.

http://codeigniter.com/tutorials/watch/blog/


Creating a Controller

A controller is simply a class that extends the CI Controller class. Copy/Paste? the code below into a new text file, change the name of the class to whatever you want to name it, and save the file into the application/controllers folder.

Here are some rules for controllers:

  • When naming the class, only the first letter shall be capitalized.
  • The filename shall be the same as the classname, except in all lowercase.
  • The first line in constructors must be parent::construct()(Just like super() in Java).
  • All controllers should have an index() function.

In the example below, the index function would be called if the user visits site.com/main in the browser. site.com/main/test_page would call the test_page function.

Constructors are not explicitly required, but needed (along with the first line)in order to inherit the methods of Controller, which gives the class the access to much of the CI core. If you need to use a model or some library that is otherwise not already loaded, you can load it in the constructor. Loading the libraries in the constructor make the libraries available for the entire class (much as you would expect). If only 1 or 2 methods in the class need a particular library, you could load it in those methods only, and wouldn't be needed in the constructor.

No matter where you load the library, it is a bad idea to load it more than once, and will often produce cryptic errors that are very hard to track down. Before calling load, check /application/autoload.php to see if it has already been loaded.

Here's an example of a Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * TIME
 *
 * TTU Integrated Metasearch Engine
 *
 * @package		TIME
 * @author		CSC3700 S11 Group
 * @copyright		Copyright (c) 2011
 * @license		http://license.here
 * @link		http://link.here
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Sandbox
 *
 * 
 * 
 * @package		TIME
 * @subpackage		Controllers
 * @author		CSC3700 S11 Group
 * @link		http://link.here
 * 
 */
class Sandbox extends CI_Controller {

	/**
	*	Constructor
	*
	* @uses Sandbox_model
	* @uses Session
	*
	* @access public
	*/
	function __construct()
	{
		parent::__construct();
		

		$this->load->model('sandbox_model');
		$this->load->library('session');
		
	}


//---------------------------------------------------------------------------
	/**
	*
	* @return void
	* @access public
	*/    
	function index()
	{
		$this->load->view('hello');
	}


//---------------------------------------------------------------------------	
	/**
	*	Test Page
	*
	*	Display a page with user-supplied title for testing purposes.
	*
	*
	*
	* @param string 	the desired page title
	* @return void
	* @author 		[If you wrote the method, place your name here]
	*
	* @access public
	*/  
	function test_page($title = '')
	{
		
		
		// Let's put something in the db
		// See documentation for insert_testrow($stuff) for the required structure of $stuff
		$stuff = array(
				'user' => $this->sandbox_model->get_sample_name(),
				'unum' => rand(0,100)
		);

		$data['title'] = 'Generic Page Title';
		$data['test_table'] = NULL; // we'll check this for null in the view file
			
		// inserts, then retrieves the table contents for display
		if( $this->sandbox_model->insert_testrow($stuff) )
		{
			// if insert above fails, this will not print
			$data['test_table'] = $this->sandbox_model->get_test_table();
		}

		// use isset() to check a variable for null before comparing it to something
		if( isset($title) && strcmp($title, '') !=0 )
		{
			$data['title'] = $title;
		}

		$data['header'] = $this->load->view('header', $data, TRUE);
		$data['content'] = $this->load->view('sandbox_page', $data, TRUE);
		$data['footer'] = $this->load->view('footer', $data, TRUE);
		
		$this->load->view('app', $data);
	}
	
}

/* End of file sandbox.php */
/* Location: ./application/controllers/sandbox.php */

Creating a Model

Same naming rules as Controllers, place file in the /application/models folder. Here's a Model that works with the above Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * TIME
 *
 * TTU Integrated Metasearch Engine
 *
 * @package		TIME
 * @author		CSC3700 S11 Group
 * @copyright		Copyright (c) 2011
 * @license		http://license.here
 * @link		http://link.here
 * @since		Version 1.0
 * @filesource
 */
 
 
// ------------------------------------------------------------------------
/**
 * Sandbox Model
 *
 * 
 * 
 * @package		TIME
 * @subpackage		Models
 * @author		CSC3700 S11 Group
 * @link		http://link.here
 * 
 */
class Sandbox_model extends CI_Model {

	/**
	*	Constructor
	*
	*
	* @access public
	*/
	function __construct()
	{
		parent::__construct();
	}
	
	
//---------------------------------------------------------------------------
	/**
	*	Insert Test Row
	*
	*	Slightly modifies, then inserts the user-supplied data into testing_table
	*
	*
	*	input:
	*	$data = array(
	*		'user' => 'Joe Smith',
	*		'unum' => 42
	*	
	*	);
	*
	* @param mixed 	the input array
	* @return boolean true on succesful insert
	* @author 		[If you wrote the method, place your name here]
	*
	* @access public
	*/  
	function insert_testrow($data)
	{
		// declare an empty row array
		// note that the keys match column names in test_table
		$row = array(
			'user_name' => '',
			'user_num' => 0
		);
		
		// remove internal spaces, convert to lower case and append a number%10
		// ex: Joe Smith with unum of 42 would become joesmith4
		$name = strtolower( str_replace(' ', '', $data['user']) ) . ($data['unum']%10);
		
		
		$row['user_name'] = $name;
		$row['user_num'] = $data['unum'] * 1000;
		
		// for this to work, $row must contain matching key names 
		// for all fields in testing_table that:
		// - do not have default values
		// - do not accept null values
		$this->db->insert('testing_table', $row);
		
		// if entry was successful, the line below will return the value of test_id
		// test_id is an autoincrement field
		$status = $this->db->insert_id();

		//return a boolean using this expression
		return ($status != 0);
	}
	
	
//---------------------------------------------------------------------------
	/**
	*	Get Test Table
	*
	*	Returns the contents of testing_table
	*	equivalent to : SELECT * FROM testing_table
	*
	*
	* @return mixed the result object
	* @author 		[If you wrote the method, place your name here]
	*
	* @access public
	*/  
	function get_test_table()
	{
		$query = $this->db->get('testing_table');
		return $query->result();

	}		
	
	
//---------------------------------------------------------------------------
	/**
	*	Get Test Table as Array
	*
	*	Returns the contents of testing_table in an associative array
	*	equivalent to : SELECT * FROM testing_table
	*
	*
	* @return mixed the result array (2D associative array)
	* @author 		[If you wrote the method, place your name here]
	*
	* @access public
	*/  
	function get_test_table_arr()
	{
		$query = $this->db->get('testing_table');
		return $query->result_array();
	}		
	
//---------------------------------------------------------------------------
	/**
	*	Get Sample Name
	*
	*	Returns a sample first name and last name
	*	ex: John Smith
	*
	* @return string	a random name built from the internal arrays
	* @author 		[If you wrote the method, place your name here]
	*
	* @access public
	*/  
	function get_sample_name()
	{
		$this->load->helper('array');
		
		$fnames = array(
			'Joe','Bobby','Pedro','Sam',
			'Mary','Alex','Chris','John',
			'Barney','Adam','Jules','Melissa'
		);
		
		$lnames = array(
			'Wilson','Smith','Jefferson','Brown',
			'Curtis','Adams','Maxwell'
		);
	
		// call the helper functions like this
		return ( random_element($fnames). ' ' .random_element($lnames) );
	}

	
}//end class

/* End of file sandbox_model.php */
/* Location: ./application/models/sandbox_model.php */

Putting It All Together

Note that in the controller, there was code as such:

	$data['header'] = $this->load->view('header', $data, TRUE);
	$data['content'] = $this->load->view('sandbox_page', $data, TRUE);
	$data['footer'] = $this->load->view('footer', $data, TRUE);
		
	$this->load->view('app', $data);

$this->load->view() was passed 3 parameters in the first 3 lines and 2 in the last. The first parameter is a string corresponding to the filename of a file in application/views (minus .php). This parameter is relative to the views folder, so if you wanted to call a file in the forms subfolder, you'd pass it 'forms/viewname'.

When the second line is called, the code in the view 'sandbox_page' has access to all the code in the 'header' view. Since we placed the first line in $data\['header'\], on the second and subsequent lines, we can access it using $header, as if it were a regular php variable. The following lines have access to everything collected in the previous lines.

The second parameter is (for our purposes) always an associative array. Notice that as we pass it to different views, we are continuously adding to it, using different key names like 'header', 'content', 'footer'. In this example, the elements of $data contain different pieces of code used to create a web page, so on the last call, we'll pass $data to the 'app' view, which will output a complete dynamically-generated HTML page.

The third parameter is boolean FALSE by default. Passing TRUE tells the loader we want to place the output in a variable. Otherwise, as is in the last line, it will output to the web browser. The only code in the 'app' view is as follows:

app.php

<?php
echo $header;
echo $content;
echo $footer;
?>

Here are the other views used (note that HTML can also be used by itself):

header.php

<!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">
<head>
<title><?php echo $title;?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/style.css" media="screen" />
</head>

<body>
<img src="<?php echo base_url();?>assets/img/ttutime.png" />

footer.php

<div id="ftr">
the footer<br />
</div>

</body>
</html>

sandbox_page.php

<?php 
	if ( ! isset($test_table) )// check for null
	{
		// remember, in the controller if the insert returns false, 
		// we assigned NULL to $test_table

		echo 'Problem inserting the data';
	}
	else
	{
		foreach($test_table as $row)
		{
			if( $row->active )
			{
				$active = 'active';
			}
			else
			{
				$active = 'inactive';
			}
			echo '<br />'.
				'id:' .$row->test_id.
				' username: '.$row->user_name.
				' usernum: '.$row->user_num.
				' status: '.$active;
			
		}
	}
?>

These files are also at the dev site in their respective locations.

Last modified 7 years ago Last modified on Mar 22, 2011, 12:20:31 AM