Blog: CodeIgniter 1.7

  • Developing a Website with CodeIgniter Part 4: Admin Site CRUD

    Jan 30, 2010

    This screencast continues a series with the goal of documenting the development of a functionally complete site using PHP with the CodeIgniter framework and jQuery for JavaScript UI Improvements including AJAX interactions.

    This video covers the development of an admin user management system (CRUD) and includes updates to the authentication system including a method that is used allow only admins into specific sections of the site.

    Download the Source Here

  • Managing Assets with CodeIgniter

    Nov 23, 2009

    This article discusses the reason behind the base_url() method and the creation of a helper file that will assist in managing images, css files, and more.

    PHP code is far from the only content necessary for most web applications. Most frequently we need to include images, css files, flash files, and many other types of files. The CodeIgniter framework doesn't contain a built-in methodology for asset management, leaving the developer to their own devices when it comes to deciding where to put this content. Every developer is going to have their own personal preference, and for the most part they're equally valid.

    The base_url() method

    Imagine a scenario where you have developed a site that contains user profiles. Each user profile can have an image. The code in your view that would display the image may look something like this:

    <img src="/images/profiles/myface.jpg" alt="" />
    

    This works fine until your cool new site is bought up and now your application rests at http://www.bigcompany.com/mycoolsite. Now, you have to go through all of your code and search/replace "/images with "/mycoolsite/images while hoping that you've found everything and that something small won't be missed until 500 users have seen it.

    Instead, we use the base_url() method for creating absolute links. base_url() simply outputs the value of the $config['base_url'] variable that is set in your application/config/config.php file. Your new code would look like this:

    <img src="<?=base_url()?>images/profiles/myface.jpg" alt="" />
    

    Now, if you need to change the location of your site you can simply update the $config['base_url'] value in your application/config.php and your code will be updated throughout the site. For this reason it's a good idea to use base_url() anywhere that you would use an absolute or relative url that points to your CodeIgniter site.

    <form action="<?=base_url()?>admin/users/edit/72" method="post">
    <a href="<?=base_url()?>admin/pages">Manage Pages</a>
    

    The asset_url() function

    We not only have to consider that our application may be moving, we need to consider how we're keeping our static assets mobile, things like images, css files, etc. My method is to create a path_helper that contains a new function, asset_url().

    // application/helpers/path_helper.php
    if (!function_exists('asset_url'))
    {   
        function asset_url()
        {
            // the helper function doesn't have access to $this, so we need to get a reference to the 
            // CodeIgniter instance.  We'll store that reference as $CI and use it instead of $this
            $CI =& get_instance();
    
            // return the asset_url
            return base_url() . $CI->config->item('asset_path');
        }
    }
    

    Then, in either our config.php or in a new configuration file we would add:

    // config.php
    $config['asset_path'] = 'system/application/assets/';
    

    Now, we just add the path_helper and the configuration file (if you're not using config.php) to the autoload.php file.

    // Note that you omit the _helper.php suffix from the filename when loading helpers, it's automatically added by CodeIgniter.
    $autoload['helper'] = array('form', 'url', 'path');
    
    // This line doesn't need to be use if you modified the config.php file, as it's already loaded for you.
    // This line configures application/config/site.cfg to be autoloaded on every page load.
    $autoload['config'] = array('site');
    

    Now that the helper has been created, the configuration updated, and everything set to autoload we're ready to use the asset_url() method. Here's the new way of writing image source.

    <img src="<?=asset_url()?>images/profiles/myface.jpg" alt="" />
    

    Now, the asset root folder can be moved anywhere you'd like and you'll be able to easily move these files around. This can be very useful if users are uploading images to your live site and you wish to view them on your dev site as well. You could simply update your configuration so that instead of use base_url() it uses http://www.mysite.com/ so that asset requests hit your live site instead of the local development site.

    A Quick Note on Preference

    Naturally, all programmers prefer to do things differently. Some prefer the asset_url set to './' so that the images/ folder is at the same place as the CodeIgniter system/ folder. I personally prefer to place assets under the application folder as shown below:

    system/application/assets/images system/application/assets/js system/application/assets/swf

    I am of the opinion that the entirety of a site should be contained within the application/ folder, allowing for the rest of the CodeIgniter structure to be replaced (version upgrade) simply. It's always important to consider the cost of maintaining the site in the future. It doesn't cost any extra time to implement good practices during development but it can be very costly to retrofit a site with similar functionality, especially if there's been personnel changes.

    The mark of a professional developer is designing and developing with focus on the lifetime cost of the product.

    If you have any questions or suggestions please leave a comment.

  • Developing a Website with CodeIgniter Part 3: The Login Process

    Nov 9, 2009

    This screencast continues a series with the goal of documenting the development of a functionally complete site using PHP with the Code Igniter framework and jQuery for Javascript UI improvements including AJAX interactions.

    In this video we utilize the user model that we've created to create a login process for our website. We'll use the code igniter form helper, database library, and session library.

    I tried something different and recorded the video in HD.  The encoding left the dark background text a bit hard to read, so if I continue to upload HD videos I'll switch to using a white background.  Please let me know if you prefer the old resolution or the HD resolution.

    Download the Source Here

  • Why Should I Use CodeIgniter?

    Oct 28, 2009

    CodeIgniter is a PHP development framework. You can think of it as a PHP web site without content. Instead it provides a structure and many methods that will be frequently used for most web sites.

    So, why should I use CodeIgniter instead of just writing my own site from scratch in PHP?

    1. Standardization and Popularity - Using a popular development framework reduces the development time and consequently cost of initial development and maintenance.

    Hiring good developers is hard and adding developers mid-project is even harder. Dozens, maybe even hundreds, of hours are spent acclimating new developers to the code base. By hiring developers who are already familiar with CodeIgniter you're able to integrate them into the project much more quickly. CodeIgniter is very compartmentalized and finding / modifying various bits of code should be very easy for anyone familiar with the framework. Initial project development time can be reduced by partially bypassing the need for planning of a custom framework.

    CodeIgniter is a framework that is widely used and it's easy to find developers who are familiar with it. There are many well made libraries and helpers created by users that will allow developers to integrate functionality into their sites without having to write it all from scratch. The CodeIgniter forums provide a centralized location for developers to get support from other developers.

    2. Loose Coupling and Code Re-usability - The longer you develop your code base the quicker projects can be completed.

    By keeping your database interactions in libraries and models, your html and display logic in views, and additional methods in helpers and plugins your resulting code becomes modular and is easily reusable on additional projects. Why rewrite your user authentication system from project to project when you can simply copy your database structure and user model and be done with it?

    CodeIgniter is written with object oriented PHP. Object oriented code is significantly less expensive to develop, debug, and maintain. Programmers can no longer get away with using global variables to pass data around the application and the project quality benefits significantly.

    3. Built in Functionality - You know those hundred things that you rewrite every time you make a site? Yea, they're already done.

    CodeIgniter comes out of the metaphorical box with libraries and helpers that reduce the amount of code a developer will have to write. Some examples of the functionality that comes bundled in are: benchmarking, html calendar generation, shopping cart management, email sending, file uploading, form validation, ftp transfers, html generation, form generation, internationalization, pagination, session management, trackback management, string / typography manipulation, and more than I can list here.

  • Using CodeIgniter's Active Record Class to Create Subqueries

    Sep 18, 2009

    A good friend of mine recently asked me how he would create a subquery using Code Igniter's Active Record class.  This does present a challenge as Code Igniter's Active Record class does not natively support subqueries.

    However, if you look into the code for the Database class you'll see that CI uses some handy utility methods to compile the SQL for processing.  These methods exist in all Code Igniter drivers (providing the cross platform abstraction that makes Active Record so valuable in the first place).

    This algorithm is definitely far from perfect, but it DOES provide some level of abstraction that manually typing your subquery would not.  If you have any questions, concerns, or suggestions feel free to leave them as comments.

    // Generate the subquery
    $this->db->select('count(*)');
    $this->db->from('users');
    
    // Render the subquery to a string
    $subQuery = $this->db->_compile_select();
    
    // Reset active record
    $this->db->_reset_select();
    
    // Generate the primary query and include the subquery
    $this->db->select('users.id as userId, users.fullname as userName');
    $this->db->select("($subQuery) as userCount");
    $this->db->where('users.status', 'active');
    

    To break this down into smaller parts:

    // Generate the subquery
    $this->db->select('count(*)');
    $this->db->from('users');
    

    This code generates the query: select count(*) from users

    // Render the subquery to a string
    $subQuery = $this->db->_compile_select();
    

    This code uses Code Igniter's Active Record class to generate an abstracted select statement. Whether we're using Oracle, MySQL, or PostgreSQL the statement will be rendered appropriately by Active Record.

    // Reset active record
    $this->db->_reset_select();
    

    This method is usually called automatically by the Active Record class after a select statement is completed. This will clear the Active Record cache so that our "select"(count(*)) and "from"(users) commands will not appear in the NEXT active record statement that we create.

    // Generate the primary query and include the subquery
    $this->db->select('users.id as userId, users.fullname as userName');
    $this->db->select("($subQuery) as userCount");
    $this->db->where('users.status', 'active');
    

    This code generates a select statement calling back the userID and the userName as well as aliasing the subquery variable string as 'userCount'. Using the MySQL driver the SQL that is output is as follows:

    SELECT `users`.`id` as userId, `users`.`fullname` as userName, (SELECT count(*) FROM (`users`)) as userCount FROM (`users`) WHERE `users`.`status` = 'active'
    

    Keep in mind that the developers of Code Igniter did not intend for you to use the _compile_select method. Therefore, it's possible that they may change the functionality in future versions and not bother letting anyone know.

  • Developing a Website with CodeIgniter Part 2: Users Database Table and the User Model

    Sep 6, 2009

    This screencast continues a series with the goal of documenting the development of a functionally complete site using PHP with the CodeIgniter framework and jQuery for Javascript UI improvements including AJAX interactions.

    This video covers the creation of a database table for storing users and the CodeIgniter model class for interacting with it.

    Errata:

    I've noticed a few errors in the screencast. When errors creep up (and they will) I'll audit them as they're discovered and keep this post up to date.  Errors will also be updated during the following screencast.

    1. The UpdateUser method "set password" line (line 80) contains the variable $options['userEmail'] instead of $options['userPassword'].
    2. The UpdateUser method is missing the line $this->db->where('userId', $options['userId']); This should be added before the line that contains $query = $this->db->update('users'); (line 84)
    3. The AddUser method's default value is set incorrectly (line 48). It currently shows array('userStatus', 'active') where it should read array('userStatus' => 'active').