I began to use code igniter a week ago and developing a site became much quicker than before. The only thing i missed was a way to build a page with the least amount of code necessary but flexible enough to use it for every site. It took me a day to come up with a viewfile based library:
- in /system/application/config/config.php i added a section
/*
|--------------------------------------------------------------------------
| Page parts
|--------------------------------------------------------------------------
|
| Configuration for Simple view library
|
| This is the basic configuration :
| $config['page'] = array('master' =>
| array('viewfile', array('page','part'));
|
| To add configuration variables for the page files :
| $config['page'] = array('master' =>
| array('viewfile', array('page','part')
| 'parts' =>
| array('partview' =>
| array('variablename' => 'variablevalue'))
| );
| master as a parts key is the hook for the variables of the master viewfile
| all as a parts key adds the variables to all the viewfiles
|
*/
- The library itself
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Sview {
function page($parts = '')
{
// function variables
$CI =& get_instance();
$config = $CI->config->item('page');
$params = array();
// add configuration values to master view file
if(isset($config['parts']['master']))
{
foreach($config['parts']['master'] as $k => $v)
{
$params[$k] = $v;
}
}
if(isset($config['parts']['all']))
{
foreach($config['parts']['all'] as $k => $v)
{
$params[$k] = $v;
}
}
// add dynamic values to master view file
foreach($parts as $k => $v)
{
// values for master view file itself
if($k == 'master')
{
foreach($v as $k2 => $v2)
{
$params[$k2] = $v2;
}
}
// values for page parts views
else
{
$partarr = array();
foreach($config['parts']['all'] as $k3 => $v3)
{
$partarr[$k3] = $v3;
}
if(isset($config['parts'][$k]))
{
if(is_array($v))
{
$arr = array_merge($v,$config['parts'][$k]);
foreach($arr as $k2 => $v2)
{
$partarr[$k2] = $v2;
}
}
else
{
foreach($config['parts'][$k] as $k2 => $v2)
{
$partarr[$k2] = $v2;
}
}
}
else
{
$partarr = $v;
}
$params[$k] = $CI->load->view($k,$partarr,true);
}
}
// check if all parts of the page in configuration are present
foreach($config['master'][1] as $part)
{
$keys = array_keys($params);
if(!is_numeric(array_search($part,$keys)))
{
$params[$part] = '';
}
}
$CI->load->view($config['master'][0],$params);
}
}
?>
I shortened the classname to sview, again to type as little as possible.
In the controller the code can be as simple as :
$this->load->library('sview');
$this->sview->page();
The array to add dynamic values into the has to have the viewfile names as keynames with the extra key master for the master viewfile.
All comments are welcome and i hope someone else can find a use for this library.
