Welcome Guest, Not a member yet? Register   Sign In
Can you access a controller method and or property from within a view?
#1

[eluser]mrbinky3000[/eluser]
Is it possible to call a controller methods and properties from inside a view?

for example:

Here is my controller

Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends Controller {

  public $s = 'Hello'

  public function __construct()
  {
     parent::__construct();
  }

  public function index()
  {
    // using the Template class
    $this->template->write_view('body','default/body',null,true);
  }

  public function _hello_world()
  {
     return $this->s.' world';
  }

}

and here is my view

Code:
<h1>test</h1>
<p>take 1 :&lt;?php echo $this->Test->_hello_world() ?&gt;</p>
<p>take 2 :&lt;?php echo $this->Test->s ?&gt; world</p>

Right now the view fails with:

Fatal error: Call to a member function _hello_world() on a non-object

Any ideas on how to get to the controller method? Is this even good practice? It seems silly to me to create a helper or library for one single method which is only related to the Test controller.

Thanks in advance.
#2

[eluser]WanWizard[/eluser]
Everything is always possible, but you shouldn't.

The idea in MVC is that models, controllers and views are independent from each other, you will make your view dependent on a test controller being there.

The CI way to do this is;
Code:
// build the data array for the view
$data = array();
$data['hello'] = $this->_hello_world();

// load the view
$this->load->view('test, $data);

then, in your view
Code:
<h1>test</h1>
<p>take 1 :&lt;?php echo $hello ?&gt;</p>




Theme © iAndrew 2016 - Forum software by © MyBB