I have class name Deal and have function inside it which name is addit
class Deal extends CI_Controller {
public function addit() {
//my function
}
}
And I have another controller name Public and I want to use function addit which belong to class Deal by extend it.
class Public extends Deal {
public function addit() {
//my function
}
}
I quite new in Codeigniter and just read few references, looking at another question on this site, and already had some answers, but I dont know which one is the best practice for it, here some solution I found:
1.Create Deal file and save at application/libraries function so another controller can use its function.
2.Create addit function on application/helper so we can use its function anywhere.
3.Create Deal file in application/core so other controller can use its function.
My question is, what is the best practice for solving my problem, and are there any other solution?
It depends on what type of function we are talking about here.
If it is about really simple function which don't do any db access or have interaction with CI components, you can create an helper :
Quote from the codeigniter documentation :
Helpers are not written in an Object Oriented format. They are simple,
procedural functions. Each helper function performs one specific task,
with no dependence on other functions.
http://www.codeigniter.com/user_guide/general/helpers.html
However, if it's a relatively complex code, then you should consider writing a library :
In application/libraries create Tools.php (or whatever you want)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tools
{
protected $ci;
public function __construct()
{
$this->ci =& get_instance();
//Allows you to access CI components
}
public function myfunction($data)
{
//If you want to use codeigniter's functionalities :
//use $this->ci->function()
}
}
And then in your controllers :
$this->load->library("tools");
$this->tools->myfunction($data);
If your library is meant to be used very often, you can load it once for all in config/autoload.php :
$autoload['libraries'] = array('database', 'tools', '...');
CI doc about libraries : http://www.codeigniter.com/user_guide/general/creating_libraries.html
Option 3 doesn't fit your problematic as you are not extending CI itself.
From comments : As the name suggests, "core" is for improving CI's core. If you don't like the way CI handles sessions for example, then you can write a new core class, however, if it's about your user management system then it concerns your app and not the framework and should be done in a lib.