base controller and apply it to all existing controller - codeigniter

I need to create codeigniter base controller to check allowed ip address in database by mobel function if the ip is exists then user should go to home page but if the ip address is not exists and show 404 page in codeigniter, i can't find core folder in application folder

First, you need to extend a core class, call it MY_Controller.php
Save that file in: application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('ip_table_model');
$this->load->library('input');
// assuming there's a function called "check_ip($ip_address)" in ip_table_model
if (!$this->ip_table_model->check_ip($this->input->ip_address()) {
redirect('error_404');
}
}
}
Now, we're assuming you have a model called ip_table_model which connects to database with list of IP addresses, and there's a function called check_ip which will validate whether user has access or not. This is relatively simple, and I won't show any examples on this.
The redirect('error_404'); page does not yet exist, you need to create a controller which shows your 404 page.
Now, for any other controllers in your project, instead of extends CI_Controller, make them extend MY_Controller instead.
Here's an example:
class Welcome extends MY_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('welcome_message');
}
}
Explanation: We're extending CI_Controller to create our own core controller, called MY_Controller. Inside, we're checking if user has access or not through the constructor, which will be called in every other controller in the project.
References:
http://codeigniter.com/user_guide/general/core_classes.html
http://codeigniter.com/user_guide/libraries/input.html

Answer is here (section Extending Core Class).
1.7.2 has a different structure to 2.0.*, therefore there is no core folder in application

In Core Create a new Class .
Name MY_Controller.php
class MY_Controller extends CI_Controller {
// Write your functions here which you wanna use throughout the website
public function abc (){
echo "Helllo";
}
}
class Welcome extends MY_Controller {
function __construct()
{
parent::__construct();
}
function your_custom_fuctions()
{
$this->abc(); //echo Hello...
//Anything you want to do
}
}

function admin_view($view_name = "", $header_info = NULL, $sidebar_info=NULL,$page_info = NULL, $footer_info = NULL, $data_info = ""){
$this->load->view('Admin/includes/header', $header_info);
$this->load->view('Admin/includes/Left_sidebar', $sidebar_info);
$this->load->view($view_name, $page_info);
$this->load->view('common/footer', $footer_info);
}

Related

White Screen When posting in CodeIgniter

Codeigniter gives a white screen every time a form is posted:
Here is the controller logic [controllers/account.php]:
class Account extends CI_Controller
{
public function create()
{
if($this->input->post(NULL, TRUE)){
$params = $this->input->post();
//add validation layer
$accountOptions = array($params are used here)
$this->load->model('account/account', 'account');
$this->account->initialize($accountOptions);
$this->account->save();
}
$header['title'] = "Create Free Account";
$this->load->view('front_end/header', $header);
$this->load->view('main_content');
$content['account_form'] = $this->load->view('forms/account_form', NULL, TRUE);
$this->load->view('account/create', $content);
$footer['extraJs'] = "account";
$this->load->view('front_end/footer', $footer);
}
}
Here is the Account Model logic [models/account/account.php]:
class Account extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function initialize($options)
{
//initialize
}
}
The view first loads fine then after filling the form and clicking submit, just white page.
I tried to add __construct to the controller and load account/account from there, the form does not even load. Any ideas?
I just found the problem:
- The Model account has duplicated definition and the error_reporting was off!
You shouldn't have two classes with the same name Account (the controller and model). Check your server and/or Codeigniter log it should show up there.
I advise you to call your controller class Account and your model class M_Account. You can then rename the model to account whenever you load it, just like you did:
$this->load->model('account/m_account', 'account');
public function __construct()
{
parent::__construct();
$this->load->model("account/account");
}
you load model,library and helper files in construct dont load to inside a function

CodeIgniter - Replace redunant JSON conversion

I recently started using Codeigniter after having a structural problem in one of my Ajax-heavy applications. (You can read up on it if you want in my previous question)
I have a fairly short question. Currently I am making a lot of Ajax requests to different controllers. I open the controllers like this:
public function __construct()
{
parent::__construct();
$this->output->set_content_type('application/json');
}
And at the end of every function I do the following:
$this->returnValue['result'] = "ReturnedInfo";
$this->returnValue = json_encode($this->returnValue);
$this->output->set_output($this->returnValue);
The code is pretty clear in itself, but I don't want to keep repeating myself. The codeigniter manual says to do the following:
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
But I would still be repeating myself. Also, I don't want to add a function to every controller that does this, even if it does decrease redundancy.
Since all of my controllers return JSON, is there a way to set this globally in a config file maybe, or in any other way?
TL;DR I have this same piece of code in every controller/function. Since the output type is always the same, just not the result, is there a way to automate this process across every controller/function?
Create an Ajax_Controller that extends MY_Controller that extends CI_Controller.
The Ajax Controller will then inherit from both Controllers.
class Ajax_Controller extends MY_Controller
{
public function __construct()
{
parent::__construct();
if(!$this->input->is_ajax_request()) return show_error('Invalid Request');
}
public function jsonOutput($json)
{
//some data checking here....
return $this->output
->set_content_type('application/json')
->set_header("HTTP/1.1 200 OK")
->set_output($json);
}
}
-
class User extends Ajax_Controller
{
public function __construct()
{
parent::__construct();
}
public function userMethod()
{
$json = json_encode(array(
'' => ''
));
$this->jsonOutput($json);
}
}
Extend your controllers from your own base class rather than CI_Controller and put your repeatedly-used function(s) and constructor code in there. Something like:
class BaseController extends CI_Controller {
protected function index() {
$this->returnValue['result'] = "ReturnedInfo";
$this->returnValue = json_encode($this->returnValue);
$this->output->set_output($this->returnValue);
}
}
class Specific extends BaseController {
public function index() {
//do controller-specific stuff
parent::index();
}
}
I abstract this further if I have groups of controllers with shared code; for example, if I had a bunch of controllers that require the user to be logged-in I create AuthenticatedController, which extends BaseController and add session checks etc.

Loading codeigniter view with predefined variables

I do not know if the following is possible. If not other suggestions are appreciated.
In nearly all my controllers I will load some default views. For example header, footer and menu.
I would like to have certain variables auto load for each view.
If I take the header as an example. Into my header I will always load an array of $css scripts and an array of $javascript files.
$javascript[] = 'js/jquery.js';
$javascript[] = 'js/jqueryui.js';
But additionally, depending on the current page logic, I might want to add another javascript file to my $javascript variable.
$javascript[] = 'js/custom.js';
Then ideally, I would like these variables to be automatically inserted as data into the load of the view.
In other words, I just want to call:
$this->load->view('header');
How could this be achieved?
Create MY_Controller add a public array there then extend from MY_Controller
class MY_Controller extends CI_Controller {
public $data;
function __construct() {
parent::__construct();
$this->data['MYVAR'] = 'Something';
}
}
in your other controllers you just do it like this
class SomeClass extends MY_Controller {
function __construct () {
parent::__construct();
}
function index () {
$this->data['SomeOtherVar'] = 'xxx';
$this->load->view('viewname', $this->data);
}
}
You can use $this->load->vars in your Controller.
I use this in my_controller and all controllers are extend from MY_Controller
For example
<?php
class MY_Controller extends Controller{
public function __construct(){
parent::__construct();
$this->setGlobalViewVariables();
}
public function setGlobalViewVariables(){
$result = array();
$result['value1'] = 'value1';
$result['value2'] = 'value1';
$this->load->vars($result);
}
}
?>
you should create an hook for this, it is very simple

Codeigniter can you tell me about MY_Controller.php and directory structure?

I am trying to learn more about CI. Yesterday I tried to implement MY_Controller.php. I read the instructions in user guide But I could not get what is the advantage of it? And one more thing I did not understand the idea use it.
I have written application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
protected $data = array();
function __construct() {
parent::__construct();
}
function render_page($view) {
//do this to don't repeat in all controllers...
$this->load->view('templates/header', $this->data);
//menu_data must contain the structure of the menu...
//you can populate it from database or helper
$this->load->view($view, $this->data);
$this->load->view('templates/footer', $this->data);
}
}
This my home controller application/controllers/home.php
class Home extends MY_Controller {
public function view($page = 'home')
{
$this->load->helper('text');
$this->data['records']= $this->services_model->getAll();
if ( ! file_exists(APPPATH.'/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page)
}
}
and my view is in in my application/views/pages/home.php.
config/routes.php:
$route['default_controller'] = 'home/view';
$route['(:any)'] = 'home/view/$1';
Now I get 404 error. My questions are:
1) why do I get 404 error?
2) if I add the about page, am I supposed to add a new controller or use the home controller?
MY_Controller Controller put into the application/core folder
Then use
MY_Controller folder path application/core/MY_Controller.php
**Home Controller ** folder path application/controllers/Home.php
class Home extends MY_Controller
to
class Home extends CI_Controller
The reason you're getting a 404 is, you did not have an index function. CodeIgniter by default loads the index function when a controller is called.
It doesn't really matter, but I would suggest you to open a new controller.
It is now working. I fixed by a clean directory structure. But i cant manage to see template/header and footer in the source code.

Load Model in HMVC

I am trying to load a model within the same module from a controller.
$this->load->model('pendingAccountModel');
but the model could not be loaded.
the module dir is accounts.
the model file path is: app/modules/accounts/models/pendingAccountModel.php
the model decleration is:
class PendingAccountModel extends Model {
function __construct(){
parent::__construct();
}
}
this is the controller who loads the model:
class PendingAccount extends MX_Controller {
function __construct(){
parent::__construct();
}
function register($data_arr)
{
$this->load->model('pendingAccountModel');
}
}
CI 1.72 with latest hmvc
Thanks
had a quick read through the HMVC docs ~
$this->load->model('pendingAccountModel');
the docs suggest that you should include the module name in the include path
so try (perhaps) $this->load->model('accounts/pendingAccountModel');
also note your "PendingAccount" controller needs to be in:
app/modules/accounts/controllers/PendingAccount.php

Resources