Welcome Guest, Not a member yet? Register   Sign In
Some functions in Controller
#1

hi, I have any controllers with some functions


PHP Code:
class Foo extends CI_Controller
{
 
  private function _bar() {
 
     // something
 
  }

I need function _bar use in other controllers. Now I useing this function _bar repeat everytime in other controllers.
How not to write one and the same function all the time?

Reply
#2

1. you can create application/core/MY_Controller.php 

and all you controllers will extend MY_Controller instead of CI_Controller

MY_Controller.php:
PHP Code:
class MY_Controller extends CI_Controller {

 
   public function __construct() {

 
       parent::__construct();
}

protected function 
yourfunction(){
 
//...
}



2. or you can use models
 put your function in a model
Reply
#3

Depending on the function of the method, putting it in a Library might be the best solution. Personally, I'd do that anyway for most things, then you could still use it within MY_Controller if needed.
Reply
#4

(11-17-2017, 09:32 AM)kilishan Wrote: Depending on the function of the method, putting it in a Library might be the best solution. Personally, I'd do that anyway for most things, then you could still use it within MY_Controller if needed.

I was find example with models...
Perfectly. I was create new Library.
Reply
#5

(11-17-2017, 08:31 AM)neuron Wrote:
PHP Code:
public function __construct() {
 
   parent::__construct();


STOP. DOING. THIS.
Reply
#6

(11-17-2017, 11:16 AM)Narf Wrote:
(11-17-2017, 08:31 AM)neuron Wrote:
PHP Code:
public function __construct() {
 
   parent::__construct();


STOP. DOING. THIS.

In Documentation :
PHP Code:
class MY_Input extends CI_Input {

 
       public function __construct()
 
       {
 
               parent::__construct();
 
       }

Reply
#7

(11-18-2017, 05:54 AM)neuron Wrote: In Documentation :
PHP Code:
class MY_Input extends CI_Input {

 
       public function __construct()
 
       {
 
               parent::__construct();
 
       }


And as the documentation says "If you need to use a constructor in your class make sure you extend the parent constructor:"

If you don't have work that must happen in a constructor then you don't need to define a constructor only for purpose of calling parent::__construct(). PHP will take care of that automatically.  

However, if you do define __construct() then you must explicitly call parent::__construct()
Reply




Theme © iAndrew 2016 - Forum software by © MyBB