CodeIgniter - constructors in models - php

So here is my controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->search_model->search_result = $_POST;
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
And here is my model:
class Search_model extends CI_Model {
protected $search_query;
function __construct($search_query)
{
parent::__construct();
$this->load->database();
$this->search_query = $search_query;
}
But this doesn't seem to work. What I want to do is pass the posted form ($_POST) to my model, then do stuff with it. But it seems messy to pass $_POST to each method of my model. My plan is to extract the variables sent with $_POST and construct these as properties such as $website_url, $text_query etc..., then call these in methods with $this->website_url;
I'm relatively new to CodeIgniter so just getting to grips with the basics

for your special purpose you can try this code
Controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->init();
}
private function init()
{
$this->search_model->init( $this->input->post() );
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
model:
class Search_model extends CI_Model {
protected $search_query;
function __construct()
{
parent::__construct();
$this->load->database();
}
public function init( $search_query )
{
$this->search_query = $search_query;
}

you have protected $search_query; which you can't access it from your controller.
You either have to change it to public or create getter and setter for it. or just getter depending on your domain/business logic.
And it should have been obvious as you should get an error saying
Fatal error: Cannot access protected property in file some/path/to/file!

Don't put the 'search query' in your model constructor.
Controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
}
public function index()
{
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
// you should probably validate/clean the post data instead
// of sending it straight to the model
$results = $this->search_model->get_where($_POST);
}
else
{
// if it's not a post, you probably need something...
// either here, or somewhere in your view to handle empty data
$results = array();
}
$data['results'] = $results
$this->load->view('search_results', $data);
}
Your Model:
class Search_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database(); // <--- you may want to autoload 'database' library
}
function get_where($where)
{
$this->db->where($where);
// add select, order, joins, etc here
return $this->db->get('mytable'); // whatever your table name is
}

Related

CodeIgniter: $data access in all views

I need to access $data[] variables in whole site, in all views. I created TestLeangue controller and assign some values to $data but in all views say that variable is not defined
class TestLanguage extends MY_Controller
{
public function __construct() {
parent::__construct();
$this->lang->load("menu","english");
}
function index() {
$data['shipping'] = $this->lang->line('menu_shipping');
$this->load->view('templates/navigation', $data);
}
}
I echo and say that I have undefined variable.
<?= $shipping; ?>
Why don't you use that data like a global variable?
class MY_Controller extends ...
{
protected $data = [];
}
Then everytime when you extend your custom controller you will have access to the general data.
class MyCustomStackOverflowController extends MY_Controller
{
public function index()
{
$this->load->view('index', $this->data);
}
}
Also, you can use $this->data to load it with general information for current controller like:
class MyCustomStackOverflowController extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->data['title'] = 'Stackoverflow';
}
public function index()
{
...
}
}
Use Index of $data as a variable name ($shipping), to get the value that you have assigned as $data['shipping']
Controller
class TestLanguage extends MY_Controller
{
public function __construct() {
parent::__construct();
$this->lang->load("menu","english");
}
function index() {
$data['shipping'] = $this->lang->line('menu_shipping');
$this->load->view('templates/navigation', $data);
}
}
View :templates/navigation
<?php
print_r($shipping);
?>

how to have variable in all view?

I use smarty and ci 3.0.6 can I use a base controller in my core? I do it but I don't have any value in my view
controller:
class MY_Controller extends CI_Controller {
public $stats;
public $title;
public function __construct() {
parent::__construct();
$this->load->model('User_Model');
$var->stats = $this->User_Model->count_Unverified_adviser();
$t=$var->stats->Unverified;
$var->title = 'title';
$this->custom_smarty->assign('vars',$var);
$this->load->vars($var);
} }
my controller that load view:
class Adviser extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->model('User_Model');
}
public function index()
{
$this->custom_smarty->assign('url',base_url());
$this->custom_smarty->display('test.tpl');
}
my test.tpl:
<td>{$vars.title}</td>
You are giving an object to the assign function.
To access $vars.title in this way you should give an array:
$this->custom_smarty->assign('vars', array( 'title' => 'somevalue' ));

Extending models in codeigniter 3

What I'm trying to do on the surface seems simple, basic OOP PHP but I just can't get it working. I have a controller class which is calling a model, that model extends another model of mine but it throws an error saying it can't find it:
Controller (Welcome.php):
public function __construct()
{
parent::__construct();
$this->load->model('users_model');
}
public function index()
{
$this->users_model->getAll();
}
Users Model (User_model.php):
class Users_model extends Base_model
{
public function __construct()
{
parent::__construct();
}
}
Base Model (Base_model.php):
class Base_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAll($table)
{
$query = $this->db->query('Query here');
return $query;
}
}
This gives me the error Fatal error: Class 'base_model' not found in /ci/application/models/Users_model.php on line 3
Save your Base_model in application/core named as Base_model.php with following code.
class Base_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAll($table=FALSE)
{
$query = $this->db->query('Query here');
return $query;
}
}
Save User_model in application/models named as User_model.php having following code
class User_model extends Base_model
{
public function __construct()
{
parent::__construct();
}
}
Then make a controller Welcome.php in appliation/controllers having following code with extending CI_Controller
public function __construct()
{
parent::__construct();
$this->load->model('user_model');//loads user_model
}
public function index()
{
$data = $this->user_model->getAll(); //need a variable to hold return data
}
You just have to locate the Base_model in your Users_model like below code and you can access the functions of base model easily.
require('application/models/base_model.php');
class User_model extends Base_model
{
function __construct()
{
parent::__construct();
}
}

CodeIgniter load database in Controller or Model?

Model :
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
public function get_all_users() {
return $this->db->get('users');
}
}
Controller :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Users_model');
}
public function index() {
redirect('users/view_users');
}
public function view_users() {
$data['query'] = $this->Users_model->get_all_users();
$this->load->view('users/view_all_users', $data);
}
}
My question is where should i put the $this->load->database? In Model or Constructor? If possible tell me why?
And one more question, if i omit the $this->load->database, the error shown
"Undefined property: Users::$db". I'm expecting "Undefined property:
Users_model::$db".
Why is that? Is it looking for $db in both controller or model?
Thank you.
Note: i can connect to database just fine. What im actually ask is if i want to use $this->load->database(). Where should i put it? Controller or Model? And why?
You can either load the database in the controller or you can load it in the model.There's not much of a difference its just more neat and clean that all the interaction in the database is in the model and the controllers the one who connects both views and model.The controller here is like a middleman between the buyer and the seller.
load database in the controller
<?php
class Test_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database('default');
$this->load->model('test_model');
}
public function index()
{
$this->db->from('test');
$query = $this->db->get();
echo "<title>CodeIgniter SQlite</title>";
$data['db']=$query->result();
//print_r($data['db']);
$count = count($data['db']);
echo "Row count: $count rows<br>";
for ($i=0; $i < $count; $i++) {
echo $data['db'][$i]->text." ";
}
}
}
?>
load database in the model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_model extends CI_Model
{
public $table1 = 'test';
public $table2 = '';
public function __construct()
{
parent::__construct();
$this->load->database('default');
}
public function check_db()
{
$this->db->from($this->table1);
$query = $this->db->get();
return $query->result();
}
}
Go to autoload.php in application/config/autoload.php and add this
$autoload['libraries'] = array('database'); // add database in array(now you dont need to load database at anywhere in project)
Make database connection settings in database.php, file located atapplication/config/database.php
now try this
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
//$this->load->database(); <----remove this
}
public function get_all_users() {
return $this->db->get('users');
}
}

Codeigniter Why I can't load view from MY_Controller

I want every controller to have a method _render_page, which loads the master template and passes the data object.
My home controller class looks like this:
class Home extends MY_Controller {
function __construct() {
parent::__construct();
}
public function index() {
$data['title'] = "Site title";
$data['the_view'] = 'welcome_message';
$this->_render_page($this->layout, $data);
//$this->load->view($this->layout, $data); //This works ok..
}
}
MY_controller class:
class MY_Controller extends CI_Controller {
public $layout;
public $viewdata;
public function __construct() {
parent::__construct();
$this->layout = 'layout/master_template';
$this->viewdata = null;
}
public function _render_page($view, $data=null, $render=false) {
$this->viewdata = $data;
$this->viewdata['the_view'] = $view;
if($this->ion_auth->logged_in()) {
$user_obj = $this->ion_auth->user()->row();
$usr_data['username'] = $user_obj->username;
$user_obj = null;
$this->viewdata['usr_data'] = $usr_data;
}
$this->load->view($this->layout, $this->viewdata); //The code crashes here
}
}
When I browse to home controller I get nothing, just white screen no errors...
Found a solution: I'm calling _render_page in a wrong way.
Instead of this:
$this->_render_page($this->layout, $data);
I should call like this:
$this->_render_page('welcome_message', $data);
Of course, that's what this function is about - to load a master page and pass the view name as member of $data, so the master page will know which view to load.
See, you need to understand the flow going,
when you call your class home , it extends MY_Controller, CI will look for MY_Controller, the constructor of your MY_controller gets executed after which CI starts executing the constructor of your home controller then your default method of home controller,
so in order to make it work you need to call _render_page()-
change your MY_Controller like -
class MY_Controller extends CI_Controller {
public $layout;
public $viewdata;
public function __construct() {
parent::__construct();
$this->layout = 'layout/master_template';
$this->viewdata = null;
$this->_render_page($this->layout, $data=null, $render=false); // call your method
}
public function _render_page($view, $data=null, $render=false) {
$this->viewdata = $data;
$this->viewdata['the_view'] = $view;
if($this->ion_auth->logged_in()) {
$user_obj = $this->ion_auth->user()->row();
$usr_data['username'] = $user_obj->username;
$user_obj = null;
$this->viewdata['usr_data'] = $usr_data;
}
$this->load->view($this->layout, $this->viewdata); //The code crashes here
}
}

Categories