• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Database driven anchor method in CodeIgniter

#1
[eluser]neillyons.co[/eluser]
Using the uri parameter search the routes table for a uri alias.

The database schema

Code:
id, route, controller, weight, created, updated


Place the following code in a new file called MY_url_helper.php ( ..system/application/helpers/MY_url_helper.php ).

Code:
function anchor($uri = '', $title = '', $attributes = '')
{
           $CI =& get_instance();
        
        $CI->load->database();

        $query = $CI->db->select('*')
                        ->from('routes')
                        ->where('controller', $uri)
                        ->order_by('weight', 'asc')
                        ->limit(1)
                        ->get();

        if ($query->num_rows() == 0)
        {
                // Perform lookup again with index suffix.
                if(count(explode('/', $uri)) == 1)
                {
                     $query = $CI->db->select('*')
                                     ->from('routes')
                                     ->where('controller', $uri.'/index')
                                     ->order_by('weight', 'asc')
                                     ->limit(1)
                                     ->get();
                }
        }

        // Assign uri alias if a match was found.
        if ($query->num_rows())
        {
                $uri = $query->row()->route;
        }
        
        
        $title = (string) $title;

        if ( ! is_array($uri))
        {
                $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
        }
        else
        {
                $site_url = site_url($uri);
        }

        if ($title == '')
        {
                $title = $site_url;
        }

        if ($attributes != '')
        {
                $attributes = _parse_attributes($attributes);
        }

        return '<a href="'.$site_url.'">'.$title.'</a>';
}

Let me know what you think of this feature in the comments.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.