Reputation:
Can someone please tell me what the best way to pass values from a controller into a view would be? If anyone has played with codeignitor, they will know what I mean. I have looked at CIs code but can't find the file that handles this. I'd LOVE to know how this is done.
Thanks!
Upvotes: 0
Views: 2661
Reputation: 1617
In Zend Framework, it's as simple as
class IndexController {
public function IndexAction {
$this->view->name='Name';
}
}
with the $this->view->xxxx setting the variable in the view.
Upvotes: 0
Reputation: 1905
You might want to try CakePHP's 15-min blog sample. I haven't tried Code Igniter.
Upvotes: 0
Reputation: 94237
There's not necessarily a "best" way as far as I know, but there is a common method that I've seen used many times, and have used myself. It generally involves an associative array, and either the extract() function or variable variables.
Basically, all you do is set up your data into an associative array, using keys that will become your template variables.
//inside the controller
$data['name'] = 'my name';
$data['zip'] = '90210';
The $data
array gets passed to the view somehow, either directly or indirectly, and extracted via extract()
or using a loop of variable variables (same thing, really). The template can then be included, and the variables are in local scope.
//inside the view rendering process
extract($data);
//$name and $zip now exist
Code Igniter follows this exact procedure. Inside system\libraries\Loader.php
in the most recent version (1.7.1) there's a function called view()
, which is what you call in your CI controller to load a view/template (same thing really in CI). You pass a data array as the second parameter.
view()
calls an internal function called _ci_load()
in the same file, which extracts the data you passed it (and does some other wacky caching stuff). Your variables are ready to go after that in the local function scope, and can be manipulated inside the template after the subsequent include()
, since everything happening in the included file exists in the local _ci_load()
function scope as well.
I've used the exact same design in a quick-and-dirty homebrew MVC set up before. It's quite effective.
Upvotes: 5