HomePHP Page 6 - Generating View from MySQL to Simulate the Model-View-Controller Schema in PHP
Putting the classes to work together: seeing the MVC schema in action - PHP
Are you a curious PHP developer, wanting to learn how to simulate a basic Model-View-Controller schema with PHP? Then, look no further, because you’re in the right place. Welcome to the final part of the series “Simulating the Model-View-Controller Schema in PHP.” In three tutorials, this series provides you with a comprehensive introduction, aimed at implementing a MVC-based relationship between PHP objects.
As I expressed in the previous section, here is an example that shows how to use all the classes that I coded before, assuming that there's a database table called "users" populated with the following data:
Now, pay attention to the code snippet below, which returns the previous data set as XHTML:
// return result set as XHTML // connect to MySQL $db=new MySQL(array ('host'=>'host','user'=>'user','password'=>'password', 'database'=>'database')); // get a result set $result=$db->query('SELECT * FROM users'); $resultController=new ResultController('xhtml'); $mysqlResult=new MySQLResult($resultController,$result); $outputGenerator=new outputGenerator($mysqlResult); echo $outputGenerator->generateOutput(); /*
Finally, here are the two scripts that return the previous MySQL result set as XML and plain text respectively:
// return result set as XML // connect to MySQL $db=new MySQL(array ('host'=>'host','user'=>'user','password'=>'password', 'database'=>'database')); // get a result set $result=$db->query('SELECT * FROM users'); $resultController=new ResultController('xml'); $mysqlResult=new MySQLResult($resultController,$result); $outputGenerator=new outputGenerator($mysqlResult); echo $outputGenerator->generateOutput();
// return result set as plain text // connect to MySQL $db=new MySQL(array ('host'=>'host','user'=>'user','password'=>'password', 'database'=>'database')); // get a result set $result=$db->query('SELECT * FROM users'); $resultController=new ResultController('plain'); $mysqlResult=new MySQLResult($resultController,$result); $outputGenerator=new outputGenerator($mysqlResult); echo $outputGenerator->generateOutput();
In this last part of this series, you've hopefully learned how to apply the MVC schema with PHP to handle MySQL data sets and generate different views or outputs from it. As I said before, this is only an introduction to this huge subject, therefore if you want to go deeper into it, there's plenty of information on the web. See you in the next PHP tutorial!