Welcome Guest, Not a member yet? Register   Sign In
Call Model function from Controller
#1

While I know the concept of MVC but I am not sure if I am doing this the most 'efficient' way
I have sql function in Model, I wan call it from Controller to pass it to View
Below is how I do the 'flow'.
Any shorter method or there a better way of doing?

Controller
PHP Code:
$participants = new ParticipantModel();
$data['participants_details'] = $participants ->participants_total();

echo view('login', $data); 


Model
PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;

class 
ParticipantModel extends Model
{
public function 
participants_total() {
// (some sql query here and return result)
}

Reply
#2

That's the right way to do it.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Well, I'd guess that too. But it doesn't work! I've spent the whole morning trying to get basic stuff like this to work ... but CI 4 seems to have broken PHP itself, or something.
Reply
#4

You need to tell your model what table to use, most of the CodeIgniter Model parameters
need to be setup in your model. I would open the system/Model.php and take a look at all
the parameters it has to offer.

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;

class 
ParticipantModel extends Model
{
    /**
     * -------------------------------------------------------------------
     * Class properties go here.
     * -------------------------------------------------------------------
     *
     * public, private, protected, static and const.
     */


    /**
     * Name of database table
     *
     * @var string
     */
    protected $table 'your_table_name';

    public function participants_total()
    {
        // (some sql query here and return result)
    }


With that you should be able to use any of the CodeIgniter Model's methods.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

Yes, I managed to make a completely dynamic API ResourceController passing in all these properties as config settings. That way I avoid having a Controller AND a Model per resource. I just config them all in a single file ... as all the basic CRUD methods are the same across a ResouceController. Will see if this bite me later down the road ... but pretty confident for now ; ).
Reply




Theme © iAndrew 2016 - Forum software by © MyBB