Making controllers in Codeigniter? - php

I have some controller in Codeigniter like this
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
function __construct()
{
parent::__construct();
// Load globals
$data->mail = new phpmailer();
$data->minified = new Minifier($vars_minified);
$this->load->vars($data);
}
public function index()
{
$this->home();
}
public function home()
{
$data['meta_title'] = seo::text($this->lang->line('home_title'), 70);
$data['body_render']='view_home';
$this->load->view("/layouts/view_layout", $data);
}
}
This is Home controller, that has __construct
Now i want to make new controller like page, but problem is with contruct , do i must repeat __construct in that controller too, or i just can put it somehow that all controllers will us that contsruct?
This is page controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
function __construct()
{
parent::__construct();
// Load globals
$data->mail = new phpmailer();
$data->minified = new Minifier($vars_minified);
$this->load->vars($data);
}
public function index()
{
$this->page();
}
public function page()
{
$data['meta_title'] = seo::text($this->lang->line('home_title'), 70);
$data['body_render']='view_page';
$this->load->view("/layouts/view_layout", $data);
}
}
You see, i have again __construct at top, is it possible to get rid of it, and make one unique __construct?

Yes it is possible please follow this guide.
When done, you can set your __construct for all Public_Controller[s], Admin_Controller[s] etc.
It is exactly what you want.
Note that after this step your variables that you send to views are going to change a bit: from $data['key'] , to $this->data['key']consider your data as "global" in scope of either Public_Controller or Admin_Controller etc.
If any troubles write a comment or read this core extending guide by ellislab or this SO thread where I mention this very same method.

Related

Codeigniter 3 MY_Controller

I have this on my MY_Controller that was located on my core folder.
<?php
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function is_logged_in($data){
$session = $this->session->userdata();
if($session['isloggedin']['username'] == ''){
return isset($session);
}else{
return FALSE;}
}
}
?>
I'm pretty sure i copy pasted the above code from some tutorial and i haven't gotten to editing it based on my needs.
Any case i have questions.
So i have a pages controller that will be responsible for giving access to some views depending on the account_type of the logged in user.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class pages extends MY_Controller {
}?>
this is my session whenever a user logs in.
$new_session = array( 'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'type' => $this->input->post('type'),
'logged_in' => TRUE);
$this->session->set_userdata($new_session);
How do i call the MY_controller function is_logged_in() from the pages controller or is the 'extends MY_Controller' automatically also calls the function is_logged_in() or do i have to basically just put it in a __construct so it automatically calls the function?
Also, how do i go about checking if a user is logged in and seeing their details?
Do i pass session_data from my controller to MY_Controller? if so, how?
Or should i just put a $this->session->userdata(); line inside the is_logged_in() function?
P.S. i have tried using Authentication Libraries but they include far too much to what i need, i just need a basic authentication. Any suggestions? that is still maintained right now.
you can directly call is_logged_in() function from your pages controller. just like this:
Pages.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends MY_Controller {
function __construct() {
parent::__construct(); // this will trigger the __construct() of MY_Controller
}
}
MY_Controller.php
<?php
class MY_Controller extends CI_Controller{
public function __construct() {
parent::__construct();
if( $this->is_logged_in() ) {
// do something if user is allowed to access.
}
else {
// do something if user is not allowed to access
}
}
}

CodeIgniter, header controller is not loading index method

Firstly I am getting no errors, I am trying to create an is_logged_in() method in my header model in Code Igniter, but nothing in the index method of the controller will load. I added die(); into it and even that wont execute, Here is my code:
header.php - controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Header extends CI_Controller {
public function index() {
print_r($this->session->all_userdata());
$data = array();
$data['title'] = 'Wenso - Timesheet';
$username = $this->session->userdata('username');
$this->load->view('template/header', $data);
$this->load->model('header_model');
$is_logged_in = $this->header_model->is_logged_in($username);
die($is_logged_in);
}
}
header_model.php - Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Header_model extends CI_Model {
public function is_logged_in($username){
$q = $this
->db
->where('email_address', $username)
->limit(1)
->get('users');
die($q->last_query());
if($q->row('username') != $username){
return FALSE;
} else {
return TRUE;
}
}
}
Note: none of the die() functions in my code work.. Anything I add into the index function of the controller (which to my understanding is loaded by default) does not get executed...
Thanks in advance
public function __construct() { parent::__construct(); }
Add this method at your model else you wont have $this->db loaded
As AdrienXL pointed out the controller is only loaded whern the url /controller_name is called.. This wasn;t the case in my user case scenario.
Also something worth pointing out as Sevtilo mentioned above if you create a construct method in CodeIgniter you ovewrite the dafult calls for things such as $this->db class, using:
public function __construct() {
parent::__contsruct();
}
Will get the parent classes contsructor.
Regards
Ric
If you want to call this code transparently (ie without having to put any extra mess in the uri) then move the code into the constructor of an extension called MY_Controller.php in application/core that looks a bit like this...
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
print_r($this->session->all_userdata());
$data = array(); $data['title'] = 'Wenso - Timesheet';
$username = $this->session->userdata('username');
$this->load->view('template/header', $data);
$this->load->model('header_model');
$is_logged_in = $this->header_model->is_logged_in($username);
die($is_logged_in);
}
}
And then in your application/controllers files extend this class like
class Some_controller extends MY_Controller{
function __construct (){
parent::__construct();
}
public function index(){
//your header code will be run before this or any other method in this class
}
}
And the code from MY_Controller.php will run before any of your methods.

calling x controller function inside a y controller function codeigniter

I'm new to codeigniter and I have two controllers: utility.phpand welcome.php.
In utility.php, I have functions:
function getdata() {
//code here
}
function logdata() {
//code here
}
Inside welcome.php, I have this function:
function showpage() {
//some code here
//call functions here
}
What I want to do is inside my welcome.php, I want to call the functions from utility.php. How do I do this? Thanks.
Refrence from here
To extend controller please either follow this tutorial or see some code below.
differences between private/public/protected
make a file in folder /application/core/ named MY_Controller.php
Within that file have some code like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data = Array(); //protected variables goes here its declaration
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE); // I keep this here so I dont have to manualy edit each controller to see profiler or not
$this->load->model('some_model'); //this can be also done in autoload...
//load helpers and everything here like form_helper etc
}
protected function protectedOne() {
}
public function publicOne() {
}
private function _privateOne() {
}
protected function render($view_file) {
$this->load->view('header_view');
if ($this->_is_admin()) $this->load->view('admin_menu_view');
$this->load->view($view_file . '_view', $this->data); //note all my view files are named <name>_view.php
$this->load->view('footer_view');
}
private function _isAdmin() {
return TRUE;
}
}
and now in any of yours existing controllers just edit 1st or 2nd line where
class <controller_name> extends MY_Controller {
and you are done
also note that all your variables that are meant to be used in view are in this variable (array) $this->data
example of some controller that is extended by MY_Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['today'] = date('Y-m-d'); //in view it will be $today;
$this->render('page/about_us'); //calling common function declared in MY_Controller
}
}
You don't is the short answer.
The point of MVC is to have your code well organized.
What you can do though is create a library in the libraries folder where you put methods you need in more than one controller.
For example you can make a mylog library, where you can put all your log related stuff. In any controller you will then call:
$this->load->library('mylog');
$this->mylog->logdata();
Besides functions that deal with data models should reside in models. You can call any model from any controller in CI
That is out of concept, if you want to call code in different controllers do following:
create helper and call function whenever (even in view) you want.
extend CI_Controller so you can use one or more functions in any controller that is extended.
Lets start with helper:
create file in folder application/helpers/summation_helper.php
use following sample of code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function sum($a, $b) {
//$CI =& get_instance();
// if you want to use $this variable you need to get instance of it so now instead of using $this->load... you may use $CI->load
$return = $a + $b;
return number_format($return, 3);
}
If you are going to use your helper in many controllers/views please load it in autoload, otherwise just load it manualy $this->load->helper('summation');
Extending Controller_CI: this is way better approach if you are using database. Please follow this tutorial, which explains it all.
*I have crafted an answer just before site went down posting this from cellphone.

How to call one controller function in another controller in codeigniter

I have one controller named home.php in which a function named podetails is there. I want to call this function in another controller user.php.
Is it possible to do so? I have read about HMVC in CI, but I want to know is it possible to do without using hmvc?
To extend controller please either follow this tutorial or see some code below.
differences between private/public/protected
make a file in folder /application/core/ named MY_Controller.php
Within that file have some code like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data = Array(); //protected variables goes here its declaration
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE); // I keep this here so I dont have to manualy edit each controller to see profiler or not
$this->load->model('some_model'); //this can be also done in autoload...
//load helpers and everything here like form_helper etc
}
protected function protectedOne() {
}
public function publicOne() {
}
private function _privateOne() {
}
protected function render($view_file) {
$this->load->view('header_view');
if ($this->_is_admin()) $this->load->view('admin_menu_view');
$this->load->view($view_file . '_view', $this->data); //note all my view files are named <name>_view.php
$this->load->view('footer_view');
}
private function _isAdmin() {
return TRUE;
}
}
and now in any of yours existing controllers just edit 1st or 2nd line where
class <controller_name> extends MY_Controller {
and you are done
also note that all your variables that are meant to be used in view are in this variable (array) $this->data
example of some controller that is extended by MY_Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['today'] = date('Y-m-d'); //in view it will be $today;
$this->render('page/about_us'); //calling common function declared in MY_Controller
}
}
write the podetails() as a function within a helper file.
then load that helper in both of the controllers.
in the controller you just call podetails()
Suppose:
--controller 1--
function podetails()
{
podetails(); // will call function in helper ;
}
--controller 2--
function podetails()
{
podetails(); // will call function in helper ;
}

CodeIgniter 'MY_' can not be found in ... error

I have been working on a session validation for my login to make sure that a user is logged in to view pages. I keep getting this error:
Fatal error: Class 'MY_Staffcontroller' not found in /usr/local/var/www/CodeTest
/ci/application/controllers/staff_c.php on line 3
My staff_c page looks like so :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Staff_c extends MY_Staffcontroller {
function homepage()
{
$data['main_content'] = 'homepage_view';
$this->load->view('includes/template', $data);
}
}
I have been reading same questions all over the place and they say the same thing pretty much...
Is your controller located in application/core?
Well yes it is. I can't seem to get passed this hump!
This is the code within My_Staffcontroller.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_staffcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
$loggedin = $this->session->userdata('loggedin');
if(!isset($loggedin) || $loggedin != TRUE);
{
die($this->load->view('denied'));
}
}
}
I know this is user error as this is only my second day with CodeIgniter but I can't seem to find proper workaround for this?
I have tried this tutorial and still nothing and also this
Even following this video has me stuck on the session part.
And I just can not get this to work.
Remember Linux is case-sensative whereas Windows is case-insensative.
place you're MY_Staffcontroller inside application/core/MY_Controller.php file
Your MY_Controller.php file should look like this (minus all you're other functions, this is a minimal example)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
}
class MY_Staffcontroller extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function sayHello()
{
echo "Hello, I am a function within MY_Staffcontroller.php";
}
}
Example
This will be located in /application/controllers directory
Basically any protected and public functions located in either MY_Controller OR MY_Staffcontroller will be accessible from derived controllers that extend the extended controller. In this case it would be MY_Staffcontroller
class Public_Staff_Controller extends MY_Staffcontroller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->sayHello();
}
}
/* end of file /application/core/MY_Controller.php */

Categories