Welcome Guest, Not a member yet? Register   Sign In
database, model loading in MVC
#1

Hi,
I want to know how often need to load / connect database / model and session in these 3 pieces of code (controller, model, view). I am facing strange even the constructor is not working :-) 
In following code, I need to connect database in every function before using a select from database, the same case with session, and model
my question is "Do I really need to connect and load (database, Model, session) in every file, ie Model, view?
for example I have main_controller, MainModel, and main_view.
main_controller:
Code:
<?php
namespace App\Controllers;
use App\Models\MainModel;

class Main_controller extends BaseController
{

  // Initialize Objects
    public function __construct(){

        $this->session = \Config\Services::session();
        $this->session->start();

        $db_name = $this->session->get("db_name");
        $db_string = $this->session->get("db_string");

        $db = \Config\Database::connect();

                if(isset($db_string)){
                        $anotherDb = \Config\Database::connect($db_string, true);
                }
                 else {
                        throw new Exception('Second database name not found.');
                 }
    }


public function index()
    {

$MainModel = new MainModel;
   
        return view('main_view');
}
}
MainModel:
Code:
use CodeIgniter\Model;

class MainModel extends Model {

public $anotherDb;
    // // Initialize Objects

public function get_school_list($school_name) {

$db = \Config\Database::connect();

$query = $db->query('SELECT * FROM school WHERE status=1 and school_string ='."'".$school_name."'");

  $row = $query->getRow();

if (isset($row)) {
    return $row;
} else
{
  return NULL;
}

  }
}

View:
Code:
<!DOCTYPE html>
<?php

use App\Models\MainModel;
    $MainModel = new MainModel;
use App\Models\Users_model;
    $Users_model = new Users_model;

     $this->data  = $MainModel->get_school_list($school_name);

    $app_name = $MainModel->get_settings('school_name');
    $aboutus = $MainModel->get_settings('about_us');
    $Twitter = $MainModel->get_settings('Twitter');
    $Facebook = $MainModel->get_settings('Facebook');
    $instagram = $MainModel->get_settings('instagram');
    $youtube = $MainModel->get_settings('youtube');

?>

<html lang="en" class="no-js">
    <!-- Begin Head -->
    <head>
        <!-- Basic -->
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title><?php echo $app_name; ?> School Management App</title>
Reply
#2

(This post was last modified: 01-28-2023, 12:04 AM by InsiteFX. Edit Reason: spelling error )

If your using a single database connection and table it is load for you when you load the your model.
You only need to load the database connection if you need to manually connect to different tables etc;
This is how to load the sessions in the BaseController.
PHP Code:
<?php

namespace App\Controllers;

use 
CodeIgniter\Controller;
use 
CodeIgniter\HTTP\CLIRequest;
use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Config\Services;
use 
Psr\Log\LoggerInterface;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *    class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
    /**
    * Instance of the main Request object.
    *
    * @var CLIRequest|IncomingRequest
    */
    protected $request;

    /**
    * An array of helpers to be loaded automatically upon
    * class instantiation. These helpers will be available
    * to all other controllers that extend BaseController.
    *
    * @var array
    */
    protected $helpers = [];

    /**
    * Be sure to declare properties for any property fetch you initialized.
    * The creation of dynamic property is deprecated in PHP 8.2.
    */
    // protected $session;

    /**
    * @var \CodeIgniter\Session\Session
    */
    protected object $session;

    /**
    * The data to be passed to the view.
    * @var array
    */
    protected array $viewData = [];

    /**
    * Constructor.
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);

        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();

        // Ensure that the session is started and running
        if (session_status() == PHP_SESSION_NONE)
        {
            // $this->session = \Config\Services::session();
            $this->session Services::session();
        }
    }


    // -------------------------------------------------------------------

}  // End of Class BaseController class.

/**
 * -----------------------------------------------------------------------
 * Filename: BaseController.php
 * Location: ./app/Controllers/BaseController.php
 * -----------------------------------------------------------------------
 */ 
What did you Try? What did you Get? What did you Expect?

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

Thanks for reply.

1. What about another database?
2. How to call a function in view? do I need to load the model in every view?
use App\Models\MainModel;
$MainModel = new MainModel;
2. what about session?

I tried to add session / another database to BaseController but no luck.
Reply
#4

If you really need a model in a view, load it in a controller and pass it to a view.
https://www.codeigniter.com/user_guide/o...o-the-view
Reply
#5

(01-28-2023, 01:21 AM)kenjis Wrote: If you really need a model in a view, load it in a controller and pass it to a view.
https://www.codeigniter.com/user_guide/o...o-the-view

In model where can I define the another / second database connection, so can be used by multiple functions in model, I tried Construct but no luck. I am using Codeigniter 4.
Reply
#6

(This post was last modified: 01-28-2023, 08:26 AM by superior.)

(01-28-2023, 08:19 AM)nadeem14375 Wrote:
(01-28-2023, 01:21 AM)kenjis Wrote: If you really need a model in a view, load it in a controller and pass it to a view.
https://www.codeigniter.com/user_guide/o...o-the-view

In model where can I define the another / second database connection, so can be used by multiple functions in model, I tried Construct but no luck. I am using Codeigniter 4.

> See: https://codeigniter.com/user_guide/datab...parameters
> See: https://codeigniter.com/user_guide/model...e-database
> See: https://codeigniter.com/user_guide/datab...-databases
Reply
#7

(01-28-2023, 08:25 AM)superior Wrote:
(01-28-2023, 08:19 AM)nadeem14375 Wrote:
(01-28-2023, 01:21 AM)kenjis Wrote: If you really need a model in a view, load it in a controller and pass it to a view.
https://www.codeigniter.com/user_guide/o...o-the-view

In model where can I define the another / second database connection, so can be used by multiple functions in model, I tried Construct but no luck. I am using Codeigniter 4.

> See: https://codeigniter.com/user_guide/datab...parameters
> See: https://codeigniter.com/user_guide/model...e-database
> See: https://codeigniter.com/user_guide/datab...-databases
Hi Superior,
Thanks for your reply.

I am talking how / where to make the connection, I can use the variable in any Method of model.

for example: the following code make the connection.
Code:
        // anotherDb -------------------
       
        $this->session = \Config\Services::session();
        $this->session->start();

        $db_name = $this->session->get("db_name");
        $db_string = $this->session->get("db_string");


       
                if(isset($db_string)){
                        $this->anotherDb = \Config\Database::connect($db_string, true);
                }
                else {
                        throw new Exception('Second database name not found.');
                }
here is a method, so I can user the $anotherDb variable to query the database. I couldn't fix this by placing the above code in Constructor.

Code:
  public function get_school_list($school_name) {

$query = $anotherDb->query('SELECT * FROM school WHERE status=1 and school_string ='."'".$school_name."'");

  $row = $query->getRow();

if (isset($row)) {
    return $row;
} else
{
  return NULL;
}

  }
Reply




Theme © iAndrew 2016 - Forum software by © MyBB