0

I am trying to learn webdesign using the MVC design pattern. Right now, I am stuck at a point where my code gets more complex, and I am unsure about the structure and where to put which code parts.

I started with an index.php file as my controller, which right now does not much more than loading the Slim framework to render the different views

$app->get('/', function() use ($app){  
$app->render('header.php');  
$app->render('content.php');   
$app->render('footer.php');  
});  
$app->run();

Then I built a complex content.php where I do a lot of form data logic, reading from a server directory, and echoing the results mixed with html tags. That surely will violate the MVC pattern, right?

What is the general approach to this? Should I put all the logic inside the index.php, store the results in an array, and pass that to the framework's render function, like this:

$app->get('/', function() use ($app){ 

//Do something and store results in an Array

$app->render('header.php', anArray());  
$app->render('content.php', anArray());   
$app->render('footer.php', anArray());  
});  
$app->run();

How can I prevent index.php becoming too complex when doing so? Is there a different approach to take?

migrated from stackoverflow.com Nov 24 '15 at 14:44

This question came from our site for professional and enthusiast programmers.

  • You might use the template feature provided my slim to seperate your view files. Take a look at the docs slimframework.com/docs/features/templates.html – VishwaKumar Nov 18 '15 at 12:42
  • In short - index.php is not the controller, it's generally just a sort of runner that fetches the relevant controller for the action you want to perform based on the URL. – CD001 Nov 18 '15 at 13:08
1

The trick is, you have to pass your variables into your object like this: $app->vars = $yourVars

Then if you include the files inside your render function the files works as part of your object and you can access your vars like this: $this->vars

Or you can also pass the vars as you thought $app->render('file.php', $yourVars)

That's the whole point of MVC you only pass specific variables to objects so they can't access all of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy