PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I am working on my first 'non trivial' PHP program and I am wondering the best way to structure the code.
I tried using functions and I even wrote my first PHP class.
However I would have dozens of 'global variables' that I don't want to pass back and forth all the time.
My main page now looks like this with many includes, but I am not too happy with this.
Also I have a big mix of php, HTML, and SQL in the same file. Is there a simple way to break these pieces apart?
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// database setup and other constants
include_once('include2.php');
if (!isset($clTableUtilities))
{
$clTableUtilities = new clTableUtilities();
}
// submit form
if ($submit == 'submit')
{
// do some validation
// no errors, perform add/update
if ($error =='N')
{
// add/updates
}
// errors, try again
else
{
// show form again with errors
}
}
// first time in
else
{
include 'listings_add1.php';
}
?>
I don't see anything that I would consider wrong there. You mention "many includes", but show just one. What others do you have (functionally)? Global variables are generally not a good thing. Classes can often avoid the use of global variables. Nothing wrong with mixing HTML, PHP and SQL, in fact you really have to do that. As feyd said, the important thing is to separate business logic from display logic, as you may often need to change one without disturbing the other.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$submit = isset($_REQUEST['submit']) ? $_REQUEST['submit'] : '';
include_once('listingsPageHeader.php');
// database setup and other constants
include_once('include2.php');
// utilities class
if (!isset($clTableUtilities))
{
$clTableUtilities = new clTableUtilities();
}
// submit form
if ($submit == 'submit')
{
include 'listings_PerformValidation.php';
// no errors, perform add/update
if ($error =='N')
{
include 'listings_AddUpdate.php';
}
// errors, try again
else
{
include 'listings_ShowForm.php';
}
}
// first time in
else
{
include 'listings_AddFirstTimeIn.php';
}
?>
Here I am mixing business rules, SQL and display logic all together. This seems typical of the examples that I have seen. How can I isolate HTML so that a graphic designer could edit HTML ; isolate SQL so DBA could modify SQL for another DB?