Load a single module of page in views codeigniter framework - php

I am developing a web app using codeigniter framework. My application has a fixed header and footer.I want to middle section (ie the body) of my application to load when the user goes to various pages which are available to him and make the header and footer constant.
(hackerrank.com ... I was talking about a website similar to this one ... after login into this website ... the header and the sidebar of this remains constant and they load the remaining page ... how can we implement it using CI framework)
Is there any way through which I can achieve this?
I am performing the following actions which is making me to load the complete website(Its like reloading the entire page :/)
As You can see the following code is present in my template.php
<?php
$this->load->view("templates/header.php");
$this->load->view($main_body);
$this->load->view("templates/footer.php");
?>
and I Controller I write the following piece of code usually
public function load_page(){
$data['main_body'] = 'dashboard_pages/dashboard_view';
$this->load->view('template.php',$data);
}

You were pretty close to the solution: Load the header and the footer as they are, variables:
<?php
$this->load->view($header);
$this->load->view($main_body);
$this->load->view($footer);
?>
The tricky thing, is that you're always writing the method function load_page() in every controller you write, and it would be better having a MY_controller, a class previous to your controller class in which you'll write which footer you're referring:
Check for writing a MY_Controller here: http://ellislab.com/codeigniter/user-guide/general/core_classes.html
Then, write your MY_Controller:
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function load_page( $page )
{
$data['main_body'] = $page;
// Logic for your header or footer deppending on logging or whatever...
if ( 1 ==1 ) {
$data['header'] = "templates/header.php";
$data['footer'] = "templates/footer.php";
}
$this->load->view('template.php',$data);
}
}
and you'll have to make sure your controllers extends MY_Controller class, and add a load_page method to whom you'll pass the argument:
class Custom_page extends MY_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load_page( 'dashboard_pages/dashboard_view' );
}
}
I think with that you'll have exactly what you look for, that way you only have to write in one place the logic for the header and footer: In MY_Controller, and just use it in any part.

Related

Called controller can't access anything

in codeigniter I have my main controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller
{
public function index()
{
$this->load->library('../controllers/forum');
$obj = new $this->forum();
$obj->test();
}
}
And the controller I'm trying to access:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Forum extends CI_Controller
{
function __construct()
{
echo "testing1";
$this->load->library('session');
parent::__construct();
$this->load->database();
$this->load->model('model_forum');
}
public function index(){
}
public function test(){
echo "testing2";
$this->data['forums'] = $this->model_forum->getForums();
$this->load->view('homepage', $this->data);
}
}
Everything is fine with my model_forum.php file, because it works if I put all the code in Main controller. But if I'm trying to access Forum controller, nothing works, only "testing1" echo goes through. Picture of error:
Anyone has any idea what I'm doing wrong? I'm new to PHP and codeigniter so I'm struggling a little bit. Thanks in advance.
You can't load a controller from a controller in CI - unless you use HMVC or something.
You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.
UPDATE
After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.
If this is the case, you'd get a cleaner solution by getting creative with your routes.
For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.
You can set up routes like this:
$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";
Then, you can call method 1 with a URL like http://example.com/method_1 and method 2 with http://example.com/method_2.
Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.
You could also go with remapping your controllers.
From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}

how to retrieve data in view Independent of controller in codeigniter

I have a sidebar in my site that receive some information from db and I can't use controller for retrieve data because I have different controller and same sidebar. How can I print this data in view page.
when I wrote in P.h.P code in the view it shows an error that it cant define variables.
How could I do this?
When you find that you need the same code in many different controllers a "custom library" (class) is the perfect choice. Documentation for creating your own libraries is found HERE.
Controllers should be using models to get data from the database. Custom libraries can also use models just like controllers. Here is a very basic custom library called Sidebar. It depends on a model (sidebar_model) that will not be shown. The purpose of the Sidebar library is to return the variables need by the sidebar_view file.
File: application/libraries/Sidebar.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sidebar
{
protected $CI; // Read the documentation link to see why this is needed.
public function __construct()
{
$this->CI = & get_instance();
$this->CI->load->database(); //only needed if not already done
$this->CI->load->model('sidebar_model');
}
public function get_sidebar_data()
{
return $this->CI->sidebar_model->get_sidebar();
}
}
The library method get_sidebar_data() returns the variables for the view.
Here is a controller that uses the custom library. It will use the custom library and a view file (not shown) containing HTML for the sidebar.
File: application/controllers/Main.php
class Main extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('sidebar'); //can also be autoloaded
}
public function index()
{
$data['sidebar'] = $this->sidebar->get_sidebar();
$this->load
->view('banner')
->view('sidebar_view', $data)
->view('main_view')
->view('footer_view');
}
}
Any other controller that needs to show the sidebar would use this same pattern.
This controller loads four different view files and is using "method chaining" which is encouraged. Method chaining executes a tiny bit faster. But the best reason for using it? Less typing.
The method chaning could also be type like this:
$this->load->view('banner')->view('sidebar_view', $data)->view('main_view')->view('footer_view');
But, IMO, putting each ->view() on a separate line makes it easier to read.
You can create a helper for your common tasks. Then create a function for your sidebar and call it where you need it. Check this link for more details about creating helper
You can also create a library for it. Although it will not a very good choice.
create sidebar (view page) and Call model directly inside that sidebar (view page).
secondly call sidebar (view page) directly inside all other view pages.

Create other pages linked to main page using codeigniter

I create a simple home page making at first the controller that point to it.Now inside the home page I have some links that point to another page.since I'm a newbie I' asking to what those link have to point?maybe to others controllers that points to another pages? If so, which could be the best way to implement those controller in the index page?
Don't understand well your question, but links to other pages are controllers/methods that build those pages.
You can also use the built-in methods to build a correct url for CI. Load the URL helper (autoload it or use $this->load->helper('url');) and you can use:
Link to page
That (the site_url() function) would build a correct (for CodeIgniter) link to www.yoursite.com/index.php/controller/method.
In your controller then you'll need to create the function (method) you asked for, and load the appropriate views.
Ex: Write an entry
will map to controllers/blog.php:
class Blog extends CI_Controller{
function write()
{
$this->load->view('write_form');
}
}
But CI's possibily the best documented framework out there, so refer to the manual and this will be soon very clear.
I think this page has all the answers for you: http://codeigniter.com/user_guide/helpers/url_helper.html
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class home extends CI_Controller {
public function __construct()
{
parent::__construct();
error_reporting(E_ALL & ~E_NOTICE);
$this->load->helper('form');
}
public function _remap()
{
$segment_1 = $this->uri->segment(1);
switch ($segment_1) {
case null:
case false:
case '':
$this->check();
break;
case 'mani':
$this->mani();
break;
default:
$this->check();
break;
}
}
public function check()
{
echo "hasgdhsad";
}
public function mani(){
echo "index";
}
}

Codeigniter - making my controllers more DRY

In my codeigniter controller function I am using the following code to generate my view and insert all the necessary content:
$left_column = $this->load->view('widgets/sub_navigation', $subnav_data, true);
$left_column .= $this->load->view('widgets/search_box', '', true); //Set data to be loaded into columns
$left_column_base = $this->load->view('widgets/assist_navigation', '', true);
$center_column = 'this is center column';
$right_column = $this->load->view('widgets/ask_us_a_question', '', true);
$right_column .= $this->load->view('widgets/newsletter', '', true);
$right_column .= $this->load->view('widgets/latest_news', '', true);
$this->template->inject_partial('left_column', $left_column); //Inject data into the partial columns
$this->template->inject_partial('left_column_base', $left_column_base);
$this->template->inject_partial('center_column', $center_column);
$this->template->inject_partial('right_column', $right_column);
$this->template->build('template',$data);
I am using a three column layout and the code above dictates what is shown in each of the columns. It works in a very modular way allowing me to customize each page quickly.
Is there a way of simplifying the above code, using arrays maybe, to cut down on repetetive code, making things more DRY??
You need to create base controllers that extend the CI_Controller. Then all your controllers extend a certain base controller you created, depending on what needs to be done in all cases that controller is called.
In application/core create a file called MY_controller.php (the prefix can be changed in config):
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
/* Widgets are only prepared -- they will be fetched and rendered once layout->render is called.
This saves the overhead of reading the files on requests where layout isn't rendered.
*/
$this->layout->prepare_widget( "widgets/navigation", "navigation_widget" );
$this->layout->prepare_widget( "widgets/footer", "footer_widget" );
$this->layout->prepare_widget( "widgets/twitter", "twitter_widget" );
}
}
class Public_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
}
}
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
if( !$this->user->has_permissions( PERMISSION_ADMIN ) )
{
redirect( base_url(), "location", 303 );
die();
}
}
}
class Member_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
if( !$this->user->has_permissions( PERMISSION_REGISTERED ) )
{
redirect( base_url(), "location", 303 );
die();
}
}
}
As you can see, all sub controllers have the widgets automatically because they extend either public, admin or member. A sub controller extending an admin controller has automatically the permissions checked so you don't need to do that ever again. You can apply this concept to your app.
A sub-controller: (placed in the normal application/controllers)
class Articles extends Member_controller {
...
}
Will have automatically ensured that the user is logged in, and the widgets are prepared without doing anything because the parent of parent class already prepared them. All you need to do in articles is to call $this->layout->render if the logic needs layout rendering at the end.
Codeigniter controllers are designed after the transaction script pattern, it's known that controller tend to get large and "not DRY" when you application grows.
To prevent such, you can re-implement the view to handle a two-step compound view pattern supporting layouts. Look for a layout view IIRC there are some on the codeigniter site.
I wrote a blog post explaining my design philosophy on organizing CodeIgniter controllers to make them more DRY. I like to have the index function of my controller serve as a common entry/exit point to avoid repeating operations that are common to all controller methods.
http://caseyflynn.com/2011/10/26/codeigniter-php-framework-how-to-organize-controllers-to-achieve-dry-principles/

Code Igniter - how would you structure this site?

I'm going to do my first site in code ignitor, a fairly basic site like this:
home
login / register
members area
protected page 1
protected page 2
protected page 3
general info section
page 1
page 2
page 3 (dynamic table of reports)
about section
page 1
page 2
blog section
listing
article page
I've gone through a couple of basic tuts and have read some of the documentation but still feel unsure on what would be the best way to structure this. Could anyone that is experienced with CI show me an example of how they' do it?
some specific Qs are:
header with nav panel will be the same on all pages. normally i'd code that as an include with if/else to show highlighted current section. I guess I'd just keep this as an include (view) and either load it first via the controller or include it in every view?
I'd envisage having a model called 'user' which will handle the login and registration, a model called 'blog' and a model called 'reports'. Does that sound right?
for static sections like about, I guess there'd be no model and i'd just have a controller with a function for each static page? i.e. about.php with page1(), page2() and all they do is load static views?
1 -> To fix this problem, I decided to use my own controller like this
Using CI 2.x, create a file under app/core called MY_Controller.php like so :
<?php
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
}
public function loadView($view) {
$this->load->view('header');
$this->load->view($view);
$this->load->view('footer');
}
}
And then I extend this controller instead of the CI one. Be sure that your $config['subclass_prefix'] = 'MY_'; in the config.php file.
2-> yes
3-> thats about it :D
I'm a newbie here (codeigniter) but:
For headers/footers I adopted the template strategy from here (first alternative). Worked nice.
Before models, I'd plan the controllers -roughly one per each section. I made all them inherit from a MY_controller here I place common funcionalilty. And yours models seems about right to me. I think them rathar as DAOs, or "service objects" that provide access to the database and not much more. GEneral intelligence of the site (if needed) should be in a custom library, or inside the controllers.
Yes.
You should use an CI library to handle your user registration and per page authorisation.
Here's a very simple example on how you could do it. Keep in mind that CI uses the MVC pattern
class Reports extends CI_Controller {
public function __construct() {
parent::__construct();
// load database if needed
// load a model if needed
}
public function page() {
//get the page requested
$page_id = $this->uri->segments(2);
// based on the page_id do something.
$data['somedata'] = 'About us data here';
// this is an actual file loaded from the template view
$data['maincontent'] = 'my_page';
$this->load->view('template',$data);
}
}
class About extends CI_Controller {
public function __construct() {
parent::__construct();
// load database if needed for this page
}
public function page() {
// same here
//get the page requested
$page_id = $this->uri->segments(2);
// based on the page_id do something.
$data['somedata'] = 'About us data here';
// this is an actual file loaded from the template view
$data['main_content'] = 'my_about_page';
$this->load->view('template',$data);
}
}
in the template file
$this->load->view('template/header');
$this->load->view('template/nav');
$this->load->view($main_content);
$this->load->view('template/footer');

Categories