Data based systems Blog

CodeIgniter (CI) PHP framework notes

CodeIgniter is a PHP (server-side) scripting framework for implementing a Model-View-Controller (MVC) architecture. To minimize scoping considerations, CodeIgniter inherits its objects from a single “super-object”.

CodeIgniter is designed for relative (rather than absolute) paths.

Configuration

local XAMPP (Apache, PHP, MySQL for Windows) development configuration

If your remote web host server uses a directory (e.g. /public_html/ ) for the publicly-visible files, it, probably, provides at least one higher-level directory in which to place your non-publicly-visible files. That higher-level directory might appear as just “ \ “; whatever the name of that higher-level, non-publicly-visible directory, it is equivalent to the \xampp\htdocs\ directory.

To emulate that production directory structure in my local XAMPP development environment, I found it easier re-specify the XAMPP DocumentRoot directory (e.g. to /htdocs/public_html/ ), instead of /htdocs/ … than to change all other paths in my local development environment. Then, when it is time to upload/FTP the local development to the remote production server, you don’t want/have to have to remember to re-change all those path references – each time you upload files.

Specify the XAMPP DocumentRoot directory in \xampp\apache\conf\httpd.conf . Around line #182, change DocumentRoot "C:/xampp/htdocs" to DocumentRoot "C:/xampp/htdocs/public_html".

That way, you do not have to set up to develop with the CodeIgniter directory tree under /htdocs/public_html/ i.e. in a publicly-visible directory.

To access SQLite3, which is bundled with PHP5, see the SQLite Notes.

local (Debian/Ubuntu) Linux Apache development configuration

To simulate a publicly-visible (e.g. /public_html/ ) production-server directory within the typical Apache local-development /var/www/ directory structure, note that the local /www/ directory corresponds to /public_html/ on the remote, production server. Thus, you can create and setup to develop in a local /var/public_html/ directory, a structure similar to the production-server’s /whatever/public_html/ directory, rather than in the Apache default /var/www/ directory.

To emulate that production directory structure in my local (Ubuntu) Linux Apache development environment, I found it easier re-specify the DocumentRoot directory (e.g. to /var/public_html/ ), instead of /var/www/ … than to change all other paths in my local development environment. Then, when it is time to upload/FTP the local development to the remote production server, you don’t want/have to have to remember to re-change all those path references – each time you upload files.

CodeIgniter configuration

    • Name/list your hosts in /etc/hosts e.g.
                  127.0.0.1   codeigniter.local
                  127.0.0.1   domain1.local
                  127.0.0.1   domain2.local
                  127.0.0.1   whatever.local
      
    • Specify the (Debian/Ubuntu) Linux Apache DocumentRoot directory in /etc/apache2/conf.d/whatever.conf (see the “ApacheNotes”) within a <VirtualHost> block e.g. to DocumentRoot "/var/public_html" … and re-start the Apache server, of course. For the result to take effect, the browser cache may have to be cleared and/or press the Reload button or CTRL R .

 

    • For development, set the base_url in: CodeIgniter/system/application/config/config.php e.g.
          $config['base_url']	= "http://whatever.local/";
      

      This setting, likely, differs on your production server.

 

    • Change the default route class using: CodeIgniter/system/application/config/routes.php
          $route['default_controller'] = "welcome";
      

      to the your CodeIgniter application default controller class name (without the .php suffix).

 

    • To omit index.php in the URL (see: Removing the index.php file ), enable the Apache mod_rewrite module (see the “ApacheNotes” “module management … on Debian/Ubuntu Linux” and “mod_rewrite” sections) and add the following in an .htaccess file, located in the DocumentRoot (index.php) directory:
              RewriteEngine on
              RewriteCond $1 !^(index\.php|images|robots\.txt)
              RewriteRule ^(.*)$ /index.php/$1 [L]
      

      For the default controller, this is not necessary; but, for URL controller calls, the .htaccess regular expressions modifications are necessary.

      If you have not placed your codeigniter directory contents to the same level as your DocumentRoot directory (e.g. /var/www/ ), you may have to adjust the third line to something like /codeigniter/index.php , rather than just index.php . Alternatively, you can change the DocumentRoot /path/to/whatever/documentRoot/directory/ designation.

    • If you Refresh at this point, you will get a 404 error, because there are no Models, Views or Controllers in the corresponding directories. If you have already (pre)written them, copy them into your directory structure, as follows:
      • models to /var/CodeIgniter/system/application/models/
      • views to /var/CodeIgniter/system/application/views/
      • controllers to /var/CodeIgniter/system/application/controllers/

 

    • To setup PHP.ini for SQLite, see the SQLiteNotes.

 

    • Edit the “Autoload Libraries” section of /CodeIgniter/system/application/config/autoload.php … and add ‘database’ to the $autoload['libraries'] array:
          $autoload['libraries'] = array('database');
      

      potential error: If your debugger says,

       
                  invalid database connection group
      

      make sure that you have specified that a database library is to be auto-loaded, as above.

 

    • Add/edit database connection groups in /CodeIgniter/system/application/config/database.php … and change the ‘default’ active_group to the currently-desired ‘active_group’ e.g. $active_group = "Dbs";In case you are copying from a previous CodeIgniter version, note that, as of about CodeIgniter version 1.7.2, one database connection group parameter was omitted and two were added.Copy/change the database connection group settings from the default template, as appropriate. In particular, within each database connection group (e.g. the ‘papers’ database connection group in this example), specifying the path to your SQLite database(s), likely, differs from your production server e.g.
          $db['papers']['database'] = "sqlite:/var/public_html/papers/articles.SQLite";
      
    • During CodeIgniter initialization all global variables are unset (see … docs: General Topics/URI Security/Register_globals) i.e. like register_globals = off.

 

  • To debug database connection issues, within a given database group in /var/CodeIgniter/system/application/config/database.php specify:
        $db['default']['db_debug'] = TRUE;
    

web host private directory configuration

If (e.g. for security) you put the /CodeIgniter/ directory tree in a directory outside your (publicly-visible) web DocumentRoot (e.g. parallel to your /htdocs/ or /public_html/ or /www/), the following configuration edits are necessary.

    • The /CodeIgniter/index.php file needs to be moved to that public web-root directory (e.g. /public_html/index.php ) – so index.php can tell the web server where to find the CodeIgniter “front controller”). See “Getting Started … with Index.php”, below.

 

    • In the index.php file, $system_folder = "system"; (~ line 27) must be changed to the relative path from the front-controller directory index.php to the new /system/ directory location e.g.
          $system_folder = "../CodeIgniter/system";
      

 

    • In the .htaccess file, adjust RewriteBase e.g. RewriteBase /public_html/ to RewriteBase / for your production site, if your production site is in your web-host DocumentRoot.potential error: If the index() page renders, but the site will not do routing, re-check the RewriteBase setting.

 

    • In /system/application/config/config.php set
          $config['base_url'] = "http://whatever.local/"
      

      ; (or to whatever desired directory). This setting will, likely, differ between your local test workstation and your production server i.e.

          $config['base_url'] = "http://yourProductionDomainName.com";
      

      on your production server.

 

    • Adjust the styles path (e.g. DBSSTYLES constant) in the CodeIgniter-controller, Articles, class constructor.

 

    • Consider defining a CodeIgniter-controller class constant (e.g. DBSARTICLES) to provide the relative path from the /views/ directory to the static HTML page directories.

 

  • Adjust (e.g. SQLite) database paths in /CodeIgniter/system/application/config/database.php

Getting started … with index.php

Now that you are “configured”, the whole sordid affair starts with index.php … either

  • \xampp\htdocs\public_html\index.php on a Windows box … or
  • /var/public_html/index.php on a *nix box.

index.php , the ‘front controller’ (see Front Controller under Controllers , below), calls the the CodeIgniter.php file i.e.

        /CodeIgniter/system/codeigniter/CodeIgniter.php

Write (or copy) your models, views and controllers into the following paths:

  • models to /var/CodeIgniter/system/application/models/
  • views to /var/CodeIgniter/system/application/views/
  • controllers to /var/CodeIgniter/system/application/controllers/

There are separate sections on Models, Views and Controllers below.

CodeIgniter run Permissions

CodeIgniter does not run under its own User or User Group. CodeIgniter is, usually, called by the web-server, usually Apache, when Apache calls its mod-php5 module. Therefore, CodeIgniter runs under the Apache User and User Group, www-data (on Debian/Ubuntu).

On a *nix box, copying (or FTPing) whatever pre-coded files, like the Models, Views, Controllers and, if you use SQLite, those pdo_*.php files, probably, was done under your login User Permissions. If you don’t change the Permissions on those copied files to at least www-data User Group Read Permission, you’ll get warnings or 404 `can’t open file errors, like:

        ... failed to open stream: Permission denied

You may get non-Permission-oriented errors, when the problem is really Permissions. Such misleading errors can waste a lot of your time troubleshooting. Change the Group Access to www-data Read-only on the directories and/or files, generating such errors. See the “LinuxNotes” and “ApacheNotes” for guidance on how to change the Permissions.

Controller & View subDirectories

If you use directories beneath the /application/controllers/ or /application/views/ directories, you must:

  • use the Controller subdirectory in the URI (making it a URL-visible segment).
  • specify the Views subdirectory in the Controller’s load->view statement e.g. $this->load->view('articles/PHPnotes.htm').

Class Constructors

PHP4 class constructor syntax uses the class name as the constructor function name.

    class Blog extends Controller
    {
        function Blog()
        {
            parent::Controller();
        }
    }

PHP5 class constructor syntax uses _construct() as the constructor function name.

    class Blog extends Controller
    {
        function __construct()
        {
            parent::Controller();
        }
    }

The above applies to Model, as well as Controller, classes.

MVC

Since a Controller can ‘control’ more than one View, a View can be used for each section (e.g. PHP ‘code island’), such as a Header, Body, Footer, Menu or Sidebar etc.). Views can be nested within one another. Child Views can inherit variables from parent Views.

Controllers

The user interface calls a Controller (not a View). A Controller may not be called from another Controller or from a Library.

Since Controllers are classes of functions, Controller names must begin with an upper-case letter, although Controller file names (e.g. class.php) need not begin with a capital letter. Controller class files are, naturally, container files where functions (e.g. implementing the business logic) reside.

The default controller function is index(), which will be called in the absence of any alternate URL controller function call.

Controllers reside in the /CodeIgniter/system/application/controllers/ directory. Subdirectories may be used, as needed.

Calling basename(dirname(__FILE__)) will return /controllers/ as the directory!

Front Controller

CodeIgniter calls its ‘front controller’ from index.php and implements its “front controller” in /CodeIgniter/system/libraries/Controller.php.

To get index.php to disappear from the URL, see http://codeigniter.com/wiki/mod_rewrite/.

If using a VirtualHost subdirectory (e.g. /CodeIgniter/ ), in .htaccess, set RewriteBase /CodeIgniter/ , rather than RewriteBase / . Even though this makes the index.php front controller disappear from the URL, index.php must still be present in the root directory i.e. above /CodeIgniter/system/.

private functions

Consistent with PHP convention, CodeIgniter uses an underscore prefix to designate private functions. Calling a private function from a URL, as follows, will not work.

    http://domain.local/index.php/class/_function

Helpers

CodeIgniter “Helpers” are non-class functions files. Helpers are procedural, rather than object-oriented code.

Libraries

CodeIgniter “Libraries” are class functions files. Libraries are object-oriented, rather than procedural code.

Models

Model represents and interacts with (e.g. insert, update, delete) a data-source, which can be joined from multiple table sources i.e. a relation , rather than, simply, from a single table i.e. there need not be a one-to-one relationship between a Model and a single table.

syntax: class name is: Model_name

	class Model_name extends Model()

An operating system Model file name should be all lower-case e.g. model_name.php. Otherwise, after FTPing from a (non-case-sensitive) Windows development PC to a (case-sensitive) Linux web host, you’ll get the error: Unable to locate the model you have specified.

A Model may not call a Controller.

CodeIgniter – Active Record database design pattern

CodeIgniter uses the ‘Active Record’ design pattern for database interaction. A database table/view is represented by a class. An object instance is ‘mapped’ to a single table/view row. After instantiating an object, a new row is added to the table upon save. Queries load a database object. Saving objects updates the corresponding/mapped table row. For example,

    part = new Part()           // instantiating a 'part' object
    part.name = "thatThing"     // assigning column values
    part.price = 123.45
    part.save()

Views

A View constructs the final presentation to the user. CI expects to find view.htm files within the /CodeIgniter/system/application/views/ directory.  If a view resides elsewhere, you must provide relative paths from the /views/ directory.   Absolute paths will not work – either absolute file system locations or relative paths from the web root.

A View may hyperlink to a Controller.

Views within views

 

Load->vars

Use in the controller constructor to specify variables for any/all views … from any function.

Load->view

Syntax example:

    $this->load->view(‘viewFileName’,$dataSource,true|false)

Load->view 2nd parameter

The load->view second parameter specifies/provides the view data , which may be an array or an object (see CodeIgniter docs: General Topics – Views). Use paths relative to the CodeIgniter/system/application/views/ directory.

Load->view 3rd parameter

(see … docs: Class Reference/Loader Class).

Value Meaning Default
False Send to browser Yes
True Return data

Options – for providing data to a view

	$this->load->view(‘viewFileName’,$viewDataSource)
	$this->load-vars($array)

The vars() option allows setting global variables in the controller constructor.  The $array variables, thus set, can be used in multiple calls from any function to any view.

URI segments

Segments are explained in the CodeIgniter User Guide … Class Reference -> URI Class section.

Styling

The xHTML <base> tag can be used to establish a base location within a single document from which to locate images and CSS; see: http://codeigniter.com/forums/viewthread/51209/

Security Sessions

To protect each Controller, either ‘Autoload’ it or call it in each Controller. Once initialized, the Session class runs automatically. Session management depends upon ‘cookies’ being enabled.

Troubleshooting

CodeIgniter logging

Change the default logging_threshold from 0 (i.e. No logging) to e.g. 4 (i.e. All messages) in /CodeIgniter/system/application/config/config.php as:

    $config['log_threshold'] = 4;

CodeIgniter logs can be viewed at: /CodeIgniter/system/logs/ .

NetBeans code completion

For each NetBeans project, add the CodeIgniter path. Right-click the project and choose Properties. In the “PHP include path” Category, add folder: /var/CodeIgnitee. Create a anyName.php file, outside /CodeIgniter/system/ with the following content:

	< ?
	/**
	* @property CI_Loader $load
	* @property CI_Form_validation $form_validation
	* @property CI_Input $input
	* @property CI_Email $email
	* @property CI_DB_active_record $db
	* @property CI_DB_forge $dbforge
	* @property CI_Table $table
	* @property CI_Session $session
	* @property CI_FTP $ftp
	* ....
	*/
	Class Controller {
	}
	?>

See: “NetBeans CI code completion”

the CodeIgniter User, Group

On Ubuntu/Debian Linux CodeIgniter operates as the www-data User. For CodeIgniter to write log files that www-data User needs Create and delete files Permissions e.g.

    sudo chmod -R 774 /var/CodeIgniter/
    chmod -$ 774 /var/public_html/

In addition to error-file logging, CodeIgniter has some error-generating functions e.g. to generate conditional error messages; see: Error handling

call CONSTANTS, rather than base_url()

Using an APP_PATH constant is many times faster than repeated base_url() function calls per: http://codeigniter.com/forums/viewthread/52448/

Strange characters

If DreamWeaver and Internet Explorer render the page, correctly, but you experience strange characters in CodeIgniter, especially, AE (Euro sign), change the character-encoding from UTF-8 to Western European.

Set DreamWeaver “Test Server” to /htdocs/CodeIgniter – not to /htdocs/CodeIgniter/system/ … or /htdocs/CodeIgniter/system/application/ etc.

file PATH errors

When you see the following error, it, usually, really means that CodeIgniter can not find the file i.e. the file path is wrong.

	Unable to load the requested file: http://whatever.htm

relative paths

Per CodeIgniter docs: Helper Reference -> File Helper , CodeIgniter uses a ‘Front Controller’ (the index.php file); paths are relative to the main/root website directory (i.e. where index.php resides).

Leave a Reply

Your email address will not be published. Required fields are marked *