Search code examples
codeigniter-4

Codeigniter 4 - call method from another controller


How to call "functionA" from "ClassA" in "functionB" inside "ClassB" ?


class Base extends BaseController
{
    public function header()
    {
        echo view('common/header');
        echo view('common/header-nav');
    }
}

class Example extends BaseController
{
    public function myfunction()
        // how to call function header from base class
        return view('internet/swiatlowod');
    }   
}

Solution

  • Well there are many ways to do this...

    One such way, might be like...

    1. Assume that example.php is the required Frontend so we will need a route to it.

    In app\Config\Routes.php we need the entry

    $routes->get('/example', 'Example::index');
    

    This lets us use the URL your-site dot com/example

    Now we need to decide how we want to use the functions in Base inside Example. So we could do the following...

    <?php namespace App\Controllers;
    
    class Example extends BaseController {
    
        protected $base;
    
        /**
        * This is the main entry point for this example.
        */
        public function index() {
            $this->base = new Base(); // Create an instance
            $this->myfunction();
        }
    
    
        public function myfunction() {
            echo $this->base->header();       // Output from header
            echo view('internet/swiatlowod'); // Output from local view
        }
    }
    

    When and where you use new Base() is up to you, but you need to use before you need it (obviously).

    You could do it in a constructor, you could do it in a parent class and extend it so it is common to a group of controllers.

    It's up to you.