As you may recall from previous posts, the MVC requires a few simple things. The biggest thing is an index.php and htaccess file working together to alter the index page depending on the url structure. For example, site.com/blog/why_am_I_a_nerd/page_2 should intuitively open site.com's blog to page 2 of the "Why am I a nerd" article.
Historically, we'd do this. We'd put a document called blog on the site and call it like this:
site.com/blog.php?title=why_am_I_a_nerd&page=2
but that is not nearly as cuil. So Using the .htaccess code to make my controller, and convert anything after the slash to a "cmd" argument, I get this:
site.com/index.php?cmd=blog/why_am_I_a_nerd/page_2
a little better. So here's how we explode that cmd argument into a page and arguments using good old php:
if($_GET[cmd]) //parse the arguments
{
if(strpos($_GET[cmd],"/") == FALSE) //if the argument has no slash in it then that's all we get
{$cmd = $_GET[cmd];}
else //if there is a slash, then we create the $cmd variable and the $array of arguments
{
$args = array();
$args = explode("/",$_GET[cmd]);
$cmd = array_shift($args); //$cmd is the first element and then the $args array just lives here to be accessed by the page at any time.
}
if (!file_exists("includes/sections/".$cmd.".php")) //we don't want a bad include
{
$cmd = null;
//here's where you'd check to see if the include can be seen due to security
}
}
if(!$_SESSION[user_name] || !$_SESSION[password]) //you are NOT logged in
{
if($cmd)
{
include_once("includes/sections/".$cmd.'.php'); //you can call args in the include
}
else
{include_once("includes/sections/login.php");}
}
else
{
if ($cmd)
{include_once("includes/sections/".$cmd.".php");} //you ARE logged in
else
{
echo "default home page";
}
}
?>
And there you have it. include file name, tested, validated, secured, and opened with a full array of arguments. This is getting fun.
Friday, November 14, 2008
Build your own MVC - easier than you think
So there are two basic components to the Controller part of Model-view-controller architecture. There's the .htaccess file which tells the server how to redirect the url request, and then there's index.php which contains hollowed out code, which will be filled in later.
First thing to realize is that there is just one page in an MVC setup. That's index.php. Everything else is an argument. What page? What data? what parameters? All arguments. Problem is no one wants to see index.php?page=page&table=table&p1=p1 in their address bar. It's ugly and bad for SEO. This is much nicer: site.com/page/table/parameter. It's easier to work with.
So let's start with the .htaccess file. This is the first stop for HTML requests when they hit your server. We want to tell the server to do what it's told, but if it can't find a corresponding page to serve, we want it to return the last segment of the url as an argument. Here's the code:
Options +FollowSymLinks
RewriteEngine On
# If requested resource does not exist as a file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?cmd=$1
That's it. If you want something more complex, you're in the wrong place. This will essentially turn site.com/p into site.com/index.php?cmd=p . Cool huh?
Next comes the index.php. You need to take the argument and use it to open an include in the index. Like so...
if ($_GET['cmd'])
{include_once("includes/sections/".$_GET[cmd].".php");}
else
{
echo "default content";
}
This essentially checks to see if there is a "cmd" identified in the URL and then opens an include with that name. If no argument is defined (just going to site.com) then it displays default content.
Voila - instant mvc. sort of. more later.
First thing to realize is that there is just one page in an MVC setup. That's index.php. Everything else is an argument. What page? What data? what parameters? All arguments. Problem is no one wants to see index.php?page=page&table=table&p1=p1 in their address bar. It's ugly and bad for SEO. This is much nicer: site.com/page/table/parameter. It's easier to work with.
So let's start with the .htaccess file. This is the first stop for HTML requests when they hit your server. We want to tell the server to do what it's told, but if it can't find a corresponding page to serve, we want it to return the last segment of the url as an argument. Here's the code:
Options +FollowSymLinks
RewriteEngine On
# If requested resource does not exist as a file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?cmd=$1
That's it. If you want something more complex, you're in the wrong place. This will essentially turn site.com/p into site.com/index.php?cmd=p . Cool huh?
Next comes the index.php. You need to take the argument and use it to open an include in the index. Like so...
if ($_GET['cmd'])
{include_once("includes/sections/".$_GET[cmd].".php");}
else
{
echo "default content";
}
This essentially checks to see if there is a "cmd" identified in the URL and then opens an include with that name. If no argument is defined (just going to site.com) then it displays default content.
Voila - instant mvc. sort of. more later.
Wednesday, November 5, 2008
Creating Tables in MySQL - A Good idea to save your restore points
Any website needs a database and any database needs tables. One very common table is the "users" table in which basic user information is stored.
**free tip ** if you find yourself making tables with lots of different data types and lots of columns, you probably are adding to the performance lag of your application. Try to only store one type of information per table. You'll thank me for it.
Another good idea is to make a php class to keep all your MySQL type stuff in. Here's one that I made:
I don't know if you can read it, but basically it is a class containing three functions, plus the constructor. There is a db_connect function which establishes the MySQL connection, the db_disconnect function, and then the recreate_user_table function. Note that the user_table function has the argument "drop" which when set to "drop" will delete the current db and create a new one.
To run your restore, just make a page called something like "recreate_user" and put this into in
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset User Table</title>
<? include_once("includes/mysql.php");?>
</head>
<body>
Hello
<? $ms = new mysql_utilities;
$ms->recreate_user_table("drop");
$ms->db_disconnect();
?>
</body>
</html>
WARNING - opening this page will delete and recreate an empty user table.
This technique will be very useful to you as you work in development and have lots of tables, and find that you need to reset your application to "like new" status.
**free tip ** if you find yourself making tables with lots of different data types and lots of columns, you probably are adding to the performance lag of your application. Try to only store one type of information per table. You'll thank me for it.
Another good idea is to make a php class to keep all your MySQL type stuff in. Here's one that I made:
<?php
class mysql_utilities{
function mysql_utilities(){
$this->db_connect();
}
function db_connect(){
//Connect To Database
$hostname='mysql.domain.com';
$username='username';
$password='password';
$dbname='dbname';
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
}
function db_disconnect(){
mysql_close();
}
function recreate_user_table($drop=""){
if ($drop=="drop")
{
$sql = 'DROP TABLE users';
$ok = mysql_query($sql);
if ($ok) {echo "User table dropped"; } else {echo mysql_error();}
}
$sql = 'CREATE TABLE `users` ('
. ' `id` BIGINT NOT NULL, '
. ' `user_name` VARCHAR(50) NOT NULL, '
. ' `password` VARCHAR(50) NOT NULL, '
. ' `email` VARCHAR(50) NOT NULL, '
. ' `entry_date` DATE NOT NULL,'
. ' PRIMARY KEY (`id`),'
. ' UNIQUE (`user_name`)'
. ' )'
. ' ENGINE = myisam;';
$ok = mysql_query($sql);
if ($ok) {echo "User table created"; } else {echo mysql_error();}
}
} //end class
?>
I don't know if you can read it, but basically it is a class containing three functions, plus the constructor. There is a db_connect function which establishes the MySQL connection, the db_disconnect function, and then the recreate_user_table function. Note that the user_table function has the argument "drop" which when set to "drop" will delete the current db and create a new one.
To run your restore, just make a page called something like "recreate_user" and put this into in
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset User Table</title>
<? include_once("includes/mysql.php");?>
</head>
<body>
Hello
<? $ms = new mysql_utilities;
$ms->recreate_user_table("drop");
$ms->db_disconnect();
?>
</body>
</html>
WARNING - opening this page will delete and recreate an empty user table.
This technique will be very useful to you as you work in development and have lots of tables, and find that you need to reset your application to "like new" status.
Your Development World
As promised, today we figure out what we need to make a website. You need Adobe CS3 or (if you feel nutty) CS4. Specifically, you need Photoshop, Fireworks, and Dreamweaver. Flash helps, but that's another nut to crack.
So you have chosen a domain, purchased it, found web hosting, and dropped a mint on software (I KNOW!) and you are ready to set up your environment. When you set up your web hosting account, after it gets approved, you'll have to choose "Windows ASP or Linux PHP" for your server type. I'm going to be talking mostly about PHP type stuff here, so that's what I would recommend you choose.
In Dreamweaver, you need to set up your new site. I'm not going to reprint the instructions on setting up your site, but create a new site in dreamweaver (using manage sites) using ftp and pointing the remote location to ftp.[your domain].com. Using your user name and password, you should be able to connect. You will also be asked to choose a local location for your site. Choose a folder with plenty of room.
Next - How do I begin
So you have chosen a domain, purchased it, found web hosting, and dropped a mint on software (I KNOW!) and you are ready to set up your environment. When you set up your web hosting account, after it gets approved, you'll have to choose "Windows ASP or Linux PHP" for your server type. I'm going to be talking mostly about PHP type stuff here, so that's what I would recommend you choose.
In Dreamweaver, you need to set up your new site. I'm not going to reprint the instructions on setting up your site, but create a new site in dreamweaver (using manage sites) using ftp and pointing the remote location to ftp.[your domain].com. Using your user name and password, you should be able to connect. You will also be asked to choose a local location for your site. Choose a folder with plenty of room.
Next - How do I begin
Tuesday, November 4, 2008
Building a Site: Step One
You have the idea, the passion, and the motivation. You want the world to see you and interact with you. The Internet is such an effective tool for communication and community development. But you - you're the idea guy - you handle the brains and hire a consultant to do all that "web" stuff. Right?
Well not anymore. Here's the way you're going to set up your empire, one step at a time. I'm going to build a site, populate it with content, and then let it fly free. And you're going to watch.
I'm assuming a few things. You have a computer and internet access (because you're reading this blog). You have the capacity to learn new things. You want to do this.
So, step 1 is to think of a name. Buy it, and set up hosting. I don't want to endorse one web hosting company over another, but Google "web hosting" company and choose the biggest bestest one that you can afford. Some examples (not necessarily endorsed) are godaddy.com, verio.com, servint.com, earthlink.net, and others. I used godaddy for "bigfishsmallbarrel.com" because they offer free hosting (with ads and it's friggin slow) with any domain name purchase. So go to one of these sites, buy a domain name and get some hosting. Use the free hosting if you can at first, so you don't have to pay while you build your stuff.
next... Your development world.
Well not anymore. Here's the way you're going to set up your empire, one step at a time. I'm going to build a site, populate it with content, and then let it fly free. And you're going to watch.
I'm assuming a few things. You have a computer and internet access (because you're reading this blog). You have the capacity to learn new things. You want to do this.
So, step 1 is to think of a name. Buy it, and set up hosting. I don't want to endorse one web hosting company over another, but Google "web hosting" company and choose the biggest bestest one that you can afford. Some examples (not necessarily endorsed) are godaddy.com, verio.com, servint.com, earthlink.net, and others. I used godaddy for "bigfishsmallbarrel.com" because they offer free hosting (with ads and it's friggin slow) with any domain name purchase. So go to one of these sites, buy a domain name and get some hosting. Use the free hosting if you can at first, so you don't have to pay while you build your stuff.
next... Your development world.
Subscribe to:
Posts (Atom)