Sandro Dolidze
Sandro Dolidze

Reputation: 177

Load PHP view file from controller with given parameters

I have a simple controller file StudentController.php

<?php

$data = array();
$data["firstName"] = $_GET["firstName"];

loadView("StudentView.php", $data);

?>

I have a even simpler view file called StudentView.php

<?php

echo $firstName;

?>

I have absolutely no idea how to implement loadView($view, $data) function. I want variables from $data in controller became available in view ($data["foo"] from controller became $foo in view)

I want achieve what is very easy to do in CodeIgniter but I have no idea how it is implemented. I tried to look into Controller.php and Loader.php in source files, but it was too messy for me to understand.

I don't want to use CodeIgniter or any other framework, I want to natively do in PHP.

Upvotes: 0

Views: 241

Answers (1)

Colin M
Colin M

Reputation: 13328

If you're going to be building a large website to be used by the general public, a framework is generally a good idea for multiple reasons:

  • Properly unit tested - generally speaking, you can be confident that the core of your website is functioning as it's intended to
  • Community support - have questions and you can easily get answers; generally these frameworks are open sourced and usually actively developed by the PHP community
  • Secure - Framework developers are, well, framework developers; and they have been trained to write code with security as a top priority

However, this question has nothing to do with frameworks vs not, so I'll answer the question you asked with a very simple function:

function loadView($view, $data) {
    extract($data);
    ob_start();
    require_once $view;
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
}

You can chose to return the contents or print them directly, but that function should do what you need. I'm making no guarantees about the security of this code, and I have obviously done no error checking. But it should serve as a great foundation to get you started.

Upvotes: 1

Related Questions