I think I speak for a number of developers when I say that I strive to have my code readable and easy to maintain. This is way easier said than done as many of you know. The most familiar way of doing this is using the Model View Controller (MVC) concept.
While I see the point in the above, I do sometimes struggle with its practicality. For example, do I really need to use CakePHP, Symfony, CodeIgniter for a simple PHP based site? I agree that frameworks can be handy for larger sites, but the majority of my sites are on the smaller side.
This is the reason that I will teach you a simple way to separate your models/views with very little OO logic, and not using a framework.
Start by creating a folder structure using the following:
<?php
// best practice is naming the class the same as the first part of the filename
class DB {
var $db; // property of our class that will store our DB connection
/*
This function loads as soon as the class is instantiated. Eg. $db = new DB();
PHP5 uses __construct and PHP4 uses a function the same name as the class. Eg. function DB()
*/
function __construct()
{
// change the following credentials to match your server
$this->db = mysqli_connect('localhost','username','password','database') or die('Unable to connect to the MySQL server.');
}
}
NOTE: Make sure you have created a database on your MySQL server and have changed it in the above class.
Now run the following SQL query on your database using any method you wish (phpMyAdmin, SSH, etc…)
CREATE TABLE IF NOT EXISTS `products` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`product_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
This creates the following fields: product_id (PRIMARY KEY), title, description, image
Do the same with the following:
INSERT INTO `trailers_products` (`product_id`, `title`, `description`) VALUES (1, 'Hosting', 'Hosting Description'), (2, 'Web Design', 'Web Design Description'), (3, 'Programming', 'Programming Description'), (4, 'SEO', 'SEO Description'), (5, 'iPhone Development', 'iPhone Development Description');
This has inserted a couple sample products so we can see our result later on.
<?php
// include our dababase class we just created
include 'db.class.php';
/*
NOTE: This class will extend the class we created previously
This means that our $db variable will be accessible for our queries ($this->db)
*/
class Products extends DB {
/*
Simple function that will get all our products from the db and return an array of objects
*/
function getProducts()
{
$query = "SELECT product_id, title, description
FROM products
ORDER BY title";
$result = mysqli_query($this->db, $query);
$data = array();
while( $row = mysqli_fetch_object($result) )
{
array_push($data, $row);
}
return $data;
}
}
<?php
// include our products class
include_once 'classes/products.class.php';
// instantiate our class
$ProdModel = new Products();
// call our user defined function which returns an array of products
$products = $ProdModel->getProducts();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Brenelz Web Solutions - Products</title>
</head>
<body>
<h1>Products</h1>
<?php foreach( $products as $p ) : ?>
<h2><?php echo $p->title?></h2>
<p><?php echo $p->description?></p>
<hr />
<?php endforeach; ?>
</body>
</html>
Now open up index.php in your browser and see all the products that have been entered into the database!
I like your simple approach. I do not agree with not using a framework type of system. Even in your simple example, you basically are creating a very basic framework, and you would have problems if they wanted to extend features on the site or have multiple pages.
Frameworks allow the ability to quickly deploy small and medium sized websites.
What frameworks do you suggest that aren’t hugely bloated like CakePHP, and Symfony. I can see using CodeIgniter possibly…
clearsilver is a pretty interesting system you might want to check out. (clearsilver.net)
Each object will have its own connection to the database?
This is similar to the Page Controller Pattern
Use Codeigniter – once you get the hang of it (which doesn’t take long), it’s really easy to work with. You only load the classes you need, so it’s really light.
Yes this is a page “controller”.
All that’s really shown here is a Model.
No front-controller. No controller for each major section of the site.
Personally, I can live without the models. The controller aspect is my favourite.
If a single “page” has a ton of features like say:
list all products, product search form, view product details etc…
accessed like site.com/products.php?cmd=list or cmd=search or cmd=view&id=37
then in the old days I’d have a ton of:
[? if($cmd===’list’){ …code… }
elseif($cmd===’view’){…code…}
elseif{…etc..} … etc…
Controllers (& a template for each controller action) are sooo much better than doing all those IFs and (to me) more important than models.
OIS: I _think_ once a connection has been made, all other attempts to connect will re-use the existing connection.
@brenelz, if you are looking for a feature rich PHP framework that isn’t huge, you should check out Dingo. It’s an open source framework I’ve been working on for the past couple years: http://www.dingoframework.com
looks pretty cool. Very similar to CodeIgniter in syntax… I guess just more of a lightweight version?
thinsoldier: you _belive_. Unlike religions you can here confirm your belief is unfounded.
1. Use PDO
2. IMO, .class.php is a silly convention, especially since the containing folder is called classes.
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!