Welcome Guest, Not a member yet? Register   Sign In
Duplicating $data in multiple functions?
#1

[eluser]Unknown[/eluser]
Hi there,

I'm pretty new to CI but not to PHP and I'm ok with the concepts of OOP with PHP, but I feel like I'm missing something REALLY obvious here...

Code:
<?php
class Login extends Controller {

function Login()
{
  parent::Controller();

  $this->load->scaffolding('users');
  $this->load->helper('form');
  $this->load->model('Login_model', '', TRUE);
  
}

function index()
{
  $data['title'] = "News Administration";
  $data['heading'] = "User Login";
  
  $data['username'] = array(
     'name'  => 'username',
     'id'    => 'username',
     'value'    => '',
     'maxlength'   => '100',
     'size'  => '15',
  );
  $data['password'] = array(
     'password'  => 'password',
     'id'    => 'password',
     'value'    => '',
     'maxlength'   => '100',
     'size'  => '15',
  );

  $this->load->view('login_view', $data);
}

function auth()
{
  $data['title'] = "News Administration";
  $data['heading'] = "User Login";
  
  if($this->session->userdata('logged_in')) {
    $this->load->view('login_sucess_view', $data);
  } else {
    $this->load->view('login_fail_view', $data);
  }
}

}
?>

Why am I duplicating $data in each function to get the information to display in the view file? Surely there must be a way of declaring that variable once and then accessing it from each function??

I tried declaring it at the top of the class and then using
Code:
$this->data
but needless to say that didnt work...

Can someone shed some light on this and put me back on the right track?

Cheers,

d.
#2

[eluser]Glen Swinfield[/eluser]
In the constructor:

Code:
$this->data = array();
$this->data['title'] = "News Administration";
$this->data['heading'] = "User Login";

Then in your actions:

Code:
if($this->session->userdata('logged_in')) {
$this->load->view('login_sucess_view', $this->data);
  } else {
$this->load->view('login_fail_view', $this->data);
  }

Should work.
#3

[eluser]Unknown[/eluser]
Cheers for the reply - thats what I tried except I had
Code:
var $data
at the top of my class and not in constructor, I'll give this a whirl and report back - many thanks! d.
#4

[eluser]Glen Swinfield[/eluser]
You could also use

Code:
var $data = array('title' => 'News Administration', 'heading' => 'User Login');

at the top of the class, then refer to it as $this->data. That would also work.




Theme © iAndrew 2016 - Forum software by © MyBB