logo sykohpath.com

				where code goes to die
			
	
tagstagstags

Web Development From Scratch, Day 3

Hey thanks for losing my really long post I did this morning!  siiigh.

After writing out a freakin' novel on setting up your environment for a basic MVC setup, I'll have to cut corners as I try to recreate this post.

1) Create the following file structure in your "www.websitetest.com" directory:
www.websitetest.com
|
|- /assets
|- /controller
|- /model
|- /view


WHY?  bah just do it. seriously.

MVC is typically reserved for "more advanced" areas, but why not do things right the first way?  Newer programmers will create scripts that contain all their code in one file, and then have that file stuck in the root directory.  Yes, the code "works", but that is not the "correct" way to go about things.

Quick MVC breakdown:  Model, View, Controller.  Breaking it down into what these three actually are:

Model: Database procedures = php + mysql
View: Frontend = html (assets will contain Javascript, CSS, and any other front-end properties)
Controller: Logic = php

With that understanding, let's see it in action.  First off, let's start off with a single-file "spaghetti-code" file.  I mean honestly, this doesn't look to scary, but imagine larger projects where everything is in one file.  Say something breaks in the logic?  Instead of scanning one large file, with MVC, you know to check your controller, which will be a much smaller file with cleaner code.

Couple notes:
* Use "mysqli" functions instead of "mysql" functions.  MySQL has been deprecated due to security issues.
* I'm using procedural style for these examples, since OOP tends to scare off newer programmers (we'll cover this later).
* While I'm using requires here, later on these are unnecessary with better techniques.  Keep this in mind: there's almost always a more efficient way of doing things!  Since it requires some OOP understanding however, let's keep it "simple" for now.

index.php
<?php

require "db_conf.php"; //load database configuration files

$mysqlDB = mysqli_connect($mysqlServerName, $mysqlUserName, $mysqlPassWord);
if(!$mysqlDB){
    die("Unable to connect: " . mysqli_connect_error());    
}

function get_all_users($db_conn){
    $sql = "SELECT * FROM users";
    $result = mysqli_query($db_conn, $sql);

    $allUsers = array();

    while($row = $mysqli_fetch_assoc($result)){
        $allUsers[] = $row['firstName'];
    }

    mysqli_free_result($result);
    
    return $allUsers;
}

$userList = get_all_users($mysqlDB);

?>
<html>
    <body>
        <?php
            foreach($userList as $value){
                echo $value, "<br>";
            }
        ?>
    </body>
</html>


Now, for MVC, we'll be splitting this up into multiple files.  Our original index.php becomes nothing more than to load the site configuration (in this case, database settings), and then load up the requested controller.  Later on, you'll be able to choose what controller to load by simply appending options to the URL (h--p://site.com/index.php/users).

index.php
<?php
    require "db_conf.php"; //load config

    require "controller/users.php"; //pass to controller
?>


Yes, only two lines of code now!  Let's have a look at the controller, which will be the first file called:

controller/users.php
<?php
    require "./model/user_database.php"; //load model

    $mysqlDB = connect_database($mysqlServerName, $mysqlUserName, $mysqlPassWord);

    $userList = get_all_users($mysqlDB);

    require "./view/all_users.php"; //pass to view
?>


Not scary at all, is it!  This is the "Logic" file, which is the main file for handling the control of the flow.  It loads the database model, calls function to connect to the database, gets all the users, and then passes control to the view.

Now, let's take care of the database functions, which are all under the Model category:

model/user_database.php
<?php
    function connect_database($server, $name, $pass){
        $link = mysqli_connect($server, $name, $pass);
        if(!$link){
            die("Unable to connect: " . mysqli_connect_error());    
        }
        return $link;
    }

    function get_all_users($db_conn){
        $sql = "SELECT * FROM users";
        $result = mysqli_query($db_conn, $sql);

        $allUsers = array();

        while($row = $mysqli_fetch_assoc($result)){
            $allUsers[] = $row['firstName'];
        }

        mysqli_free_result($result);
        
        return $allUsers;
    }
?>


Notice that the "get_all_users" function is exactly the same.  That's because it was a database function to begin-with, so no change needed.  We put the database connection routine in this file as well, since it's well, a database connection.

Finally, we have the "View":

view/all_users.php
<html>
    <body>
        <?php
            foreach($userList as $value){
                echo $value, "<br>";
            }
        ?>
    </body>
</html>


Again, this part is unchanged.  Previously, it was "tacked on" to the end of the file.  Also note that there was a whitespace before the html in the previous version...oops!

----------------------------------------------------------------------
One final note...This is completely optional, and there's arguments either way.  I won't get into gory details, but basically:  You don't, and also shouldn't end your php files with "?>".  WHY?  Several reasons:

1) There can be whitespace after the bracket.  This is the main issue.  ANY whitespace before html output can and will cause problems.  I mean, it's not difficult to make sure there isn't any trailing whitespace.
2) Zend Framework coding standards.  Get used to seeing "Zend" quite a bit in the future.  They require any file that is pure-php to not have the closing tag.
3) This is by design: PHP documentation even states that this tag is optional - useful to leave out for includes(), requires(), and output buffering.

Of course, there's reasons why you should always close the tag:
1) OCD.  Tags were made to be in sets. Open-close.  This applies to just about every other tag on the planet.
2) Can be confusing to others to not having the closed tag in there.
3) There is no 3

You may sense my bias here.  You're not a "bad programmer" if you're using/not using tags.

---------------------------------------------------------------------

Ok, so, on your web host service, let's get this setup for tomorrow.  Every host is different, but basically what you need to do is create a MySQL "test" database.  Don't need to bother with anything else in it right now, just get that created.

php, tutorial, mvc,


0 comments.