'How to use a PHP MVC Controller, one thats invoked by calling a URL, to call and execute more than one function? [duplicate]

Currently I have been teaching myself CodeIgniter3, which is a MVC framework. I am failing to understand a couple of things. One such subject that I don't understand is how to execute more than one function when I have to call functions using a URL.

FOR EXAMPLE: I have a page, or a URL rather (considering it doesn't render any content), whose sole purpose is to route dynamic requests, thus providing functionality to the website.



The Controller's URL is:
http://localhost/MyApp/index.php/Controller


The way that the controller works is by calling a function, like this:
http://localhost/MyApp/index.php/Controller/Controller-Func


To pass an argument to the function, the URL can be called like this:
http://localhost/MyApp/index.php/Controller/Controller-Func/$var

How can I call multiple functions from the same controller at the same time?



Solution 1:[1]

To better help you, I first need to details bit more how MVC works. I've never worked with CodeIgniter, but from experience with Laravel and other MVC frameworks, Model-View-Controller (MVC) design paradigm organizes your application into three main domains - the model, which usually represents the database entities and other types of encapsulated logic, the view, which generates the final output (often HTML) that the user receives, and the controller, which controls the flow of interaction between the model and the view (and may contain some logic of its own as well).

Additionally, you'll have a front controller handling all calls to your application. In this case, this is your index.php file. This front controller uses routes to map various endpoints. This is how your application links urls to controller methods.

All this means a single route (url) can typically calls only one controller method.

Now, for your specific question, it's only a matter or organizing your code so common code can be shared by multiple controller methods. You can have shared protected methods inside your controller class which can be called by both routes.

For example, your controller class can be structured like this :

public function firstPage()
{
   $foo = $this->getBar();
   // Load first page view
}

public function secondPage()
{
   $foo = $this->getBar();
   // Load second page view
}

protected function getBar()
{
   return 'Bar';
}

In this simple example, you can use the getBar method to load all data or perfrom CRUD operation shared by your two pages / controller methods, firstPage and secondPage.

In short, keep in mind a controller class and its method should be as simple and short as possible. I recommend sending more complex logic to services or other classes. For example :

protected function getBar()
{
   return new Bar();
}

In this case, it will be easier to Extend the Bar class than extending a controller class or method, if you require so. It will also help you, in the long run, when dealing with UnitTesting.

Solution 2:[2]

There are several ways to access a controller inside of another controller.


    class Test1 extends CI_controller
    {
        function testfunction(){
            return 1;
        }
    }


First, create a controller class (as shown above). Then create a second class that extends the controller class (as shown below). The example below can now be passed using a single URI.



    include 'Test1.php';
    
    class Test extends Test1
    {
        function myfunction(){
            $this->test();
            echo 1;
        }
    }



By the way, if you wanted to include your MVC's model class, then you need to create a class in the model folder, a class in controller folder, and a view file in the view folder.

This is how you would make a CRUD function:

Model:

    class Custom extends CI_Model
    {
        public function __construct()
        {
            parent::__construct(); 
        }
    
        function selectAll($Qry)
        {
            $query = $this->db->query($Qry);
            $DataRetuen = $query->result();
            if ($DataRetuen) {
                return $DataRetuen;
            } else {
                return 0;
            }
        }
    
        function Insert($Data, $idReturn, $table, $getLastId = 'N')
        {
            $insert = $this->db->insert($table, $Data);
            if ($insert) {
                if ($getLastId === 'Y') {
                    $returnValue = $this->db->insert_id();
                } elseif (!isset($Data[$idReturn]) || $Data[$idReturn] == '') {
                    $returnValue = 1;
                } else {
                    $returnValue = $Data[$idReturn];
                }
                return $returnValue;
            } else {
                return FALSE;
            }
        }
    
        function Edit($Data, $key, $value, $table)
        {
            $this->db->where($key, $value);
            $update = $this->db->update($table, $Data);
            if ($update) {
                return 1;
            } else {
                return 0;
            }
        }
     }



You can use that model in the controller as:
    class Test extends CI_controller
    {
    
        function myfunction()
        {
            $this->load->model('custom');
            $ModelCustom = new Custom();
            $Arr = array();
            $Arr['sql_key'] = 'value';
            $responseArray = $ModelCustom->Edit($Arr, 'primary_key',    'primary_key_value', 'table_in_db');
            $this->load->view('my_view', $responseArray);
        }
        
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Charette
Solution 2 j D3V