Serve multiple pages from 1 PHP file?
So basically i am struggling with the need of optimizing my code for some project of mine.
Currently i have pages like add_company.php
, view_company.php
, edit_company.php
.
What i would like to do is to serve all content from just 1 PHP file company.php
.
So to speak company.php?action=view
, company.php?action=edit
etc. Is the only way to do this with ma开发者_StackOverflowssive if else statements? That would make my company.php
like mega huge.
Or maybe even better how could I serve all my pages just using index.php ?
So what would be the best way to accomplish this? I am not php guru and i don't have much experience with MVC or any other pattern.
Thanks.
You could make company.php
<?php
$allowed = array('add', 'view', 'edit');
if ( ! isset($_GET['action'])) {
die('missing param');
}
$action = $_GET['action'];
if ( ! in_array($action, $allowed)) {
die('invalid');
}
require $action . '_' . __FILE__;
Quick and dirty, but should work :) You could place this code in any file, and it will work straight away.
With a bit of modification, you could make this your front controller with index.php
.
I always prefer using a switch statement for the $_GET variable. Its my personal preference to put all the logic pertaining to one entity (in this case company) in a single PHP file because I generally deal with tons of entities. If you want a MVC model, this might not be what you are looking for. Just my 2 cents.
// Common page header
// Other stuff common in the pages
$page_to_load = $_GET[view];
switch($page_to_load) {
case 'view':
//Logic to view or HTML for view
break;
case 'add':
//Logic to add or HTML for add
break;
}
// Common footer etc..
This is pretty simple stuff. It should look something like this:
//index.php
if (!isset($_GET['page']))
{
require('index_contents.php');
}
else if ($_GET['page'] == 'company')
{
if (!isset($_GET['action']))
{
require('company_contents.php');
}
else if ($_GET['action'] == 'edit')
{
require('edit_company.php');
}
else if ($_GET['action'] == 'add')
{
require('add_company.php');
}
else
{
require('company_contents.php');
}
}
else
{
require('index_contents.php');
}
A very easy solution would be to just use includes.
if ($_GET["action"] == "view") {
require("action_view.php");
} else if ...
(of course, you might want to use a switch statement, if you have lots of different page types)
Then action_view.php contains just the code for the specific page.
Better, but also more complicated solutions, would be an object oriented approach (abstract Page class with Factory Pattern) or forthright a good framework and template engine.
You could use POST instead of GET with index.php:
<?php
require($_POST['action'] . ".php");
?>
This would hide the action type from the user, acting as though it is a single page. However, it may require using a form in your navigation as opposed to linking direct to "company.php?action=edit".
精彩评论