FROST

FRee and Open Source Technologies

Creating your own library in CodeIgniter

Creating your own library in CodeIgniter

You setup CodeIgniter and you see how it really helps your life as a developer doing you job. But you want your codes to be reusable into your other projects. Yes you can say i'll just copy-paste the codes, but there's more elegant idea, build it as a library. What is a library, IMO, a library is a file or a component that can be easily inject into an existing system.

Nuf said, here's the code:

<?php
/**
* class for easy uploading of files for CI
* @author zeratool
* @uses CI::Upload class
*
*/

class lib_upload
{
function __construct()
{
$config['upload_path'] = '/your/path/to/upload/dir/';
$config['allowed_types'] = 'gif|jpg|png';

$this->CI =& get_instance();
$this->CI->load->library('upload', $config);
}

/**
* uploads the file
* @access public
*
*/
function do_upload()
{
$data = $this->validate();
return $data;
}

/**
* cehcks the file uploaded
* @access private
* @return mixed, string if error, array of file uploaded info on success
*/
private function validate()
{
if (! $this->CI->upload->do_upload())
{
return $this->CI->upload->display_errors();
}
else
{

return $this->CI->upload->data();
}
}

}

?>

Now in order to use our library, we have to create our Controller and View files.

First, the controller:

<?php

class upload extends Controller
{
function __construct()
{
parent::Controller();

//we use our custom library by loading it first
$this->load->library('lib_upload');
}

function index()
{
// we load our view file here, in our case it's the upload form
$this->load->view('uploadform');
}

function do_upload()
{
// we call the do_upload method of our library
$ok = $this->lib_upload->do_upload();

// we checked if the upload is successful or not
// if it displays the array of the file information, try to check your
// upload directory and look for the file there
// NOTE : you must set the upload dir enough write priveledges

echo '<pre>';
print_r($ok);

}
}

?>

Here's our View file

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?=$error;?>

<?=form_open_multipart('upload/file/do_upload'); ?>

<input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

Previously

Blog title changed

"Frameworks that work" was the old title of this humble blog. I switched to "FROST!" so I can write anything open source. Hoping for more ... read on
© FROST