• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
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.
Practical CodeIgniter 3  • CodeIgniter 4 Foundations - Coming Soon • Vulcan - CLI Tools for CI4
Reply

#4
(11-17-2017, 10: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, 09:31 AM)neuron Wrote:
PHP Code:
public function __construct() {
 
   parent::__construct();


STOP. DOING. THIS.
Reply

#6
(11-17-2017, 12:16 PM)Narf Wrote:
(11-17-2017, 09: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, 06: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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


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