next step in programming? [sample code included]

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!

Moderator: General Moderators

Post Reply
dajohnson1s
Forum Newbie
Posts: 19
Joined: Sat Nov 15, 2008 12:44 pm

next step in programming? [sample code included]

Post by dajohnson1s »

Hello,

I have been learning php for about 8ish months now, and really enjoy it thus far, but I have noticed that my skills have become somewhat stagnant, and am really not sure where to go to advance my skills. Unfortunately, I tend to follow the structure I would for a University assignment, most were very short (and procedural) and could be solved with a single 'main' function or a few secondary functions, never really touching on OO or anything like that.

I have been reading about MVC quite a bit lately, but cannot seem to conceptualize how to make my code into OOP and MVC fashion.

Here is an example page:

Code: Select all

 
<?php
    // Sets basic checks 
    if( isset( $_GET['mode'] ) && isset( $_GET['type'] ) ){
        $mode = $_GET['mode'];
        $type = $_GET['type'];
    }else{
        header( 'Location: ../start.html' );
    }
    
    require( dbconnection.php );
    error_reporting( E_ALL );
    
        $sqlIcon = "
            SELECT
                iconID,
                iconURL
            FROM
                mapItems_icons
        ";
    
    $resultIcon = mysql_query( $sqlIcon );
    if( !$resultIcon ) 
        die( mysql_error( $conn ) );
    
    if( $mode == 'edit' ){
        //populates the form fields
        
        
        $sql = "
            SELECT
                m.mapItemID,
                m.name,
                m.address,
                m.url,
                i.iconID
            FROM
                mapItems AS m
                INNER JOIN mapItems_icons AS i
                    ON m.iconID = i.iconID
            ORDER BY
                m.name ASC  
        ";
 
    }else{
        //populates the drop down
        $sql = "
            SELECT
                iconID,
                iconURL
            FROM
                mapItems_icons
        ";
    }
    $result = mysql_query( $sql );
    if( !$result ) 
        die( mysql_error( $conn ) );
    $row = mysql_fetch_array( $result, MYSQL_ASSOC );
    $iconid = $row['iconID'];
    echo $iconid;
?>
<!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>Building Information</title>
    </head>
 
    <body>
 
        <form>
            <fieldset>
                <legend>General Building Information</legend>
                <label for="buildingName">Building Name:</label>
                <input id="buildingName" type="text" size="20" value="<?php if($mode == 'edit'){ echo $row['name']; } ?>" />
                <label for="buildingAddress">Building Address:</label>
                <input id="buildingAddress" type="text" size="20" value="<?php if($mode == 'edit'){ echo $row['address']; } ?>" />
                <label for="buildingImage">Image URL:</label>
                <input for="buildingImage" type="text" size="40" value="<?php if($mode == 'edit'){ echo $row['url']; } ?>" />
            </fieldset>
            <?php if( $type == 'marker' ){ ?>
            <fieldset>
                <legend>Choose a Marker</legend>
                Select a Marker: <select>
            <?php
                //mysql_data_seek($result, 0);
                while( $row = mysql_fetch_array( $resultIcon, MYSQL_ASSOC ) ){
                    $iconID = $row['iconID'];
                    $iconURL = $row['iconURL'];
                    
                    if( $iconID == $iconid ){
                        echo "<option value=\"$iconID\" selected>{$iconURL}</option>\n";
                    }else{
                        echo "<option value=\"$iconID\">{$iconURL}</option>";
                    }
                }
            ?>
                 </select>
            </fieldset>
            <?php } ?>
            <fieldset>
                <legend>Get Coordinates</legend>
                <p>Map will populate here</p>
            </fieldset>
            <br /><br />
            <button>Submit</button>
        </form>
    </body>
</html>
 
 
With this being my second major php project, you can imagine how much fun this is to maintain later on... :(

Since I am basically just building prototypes and figuring out how I would like things to flow and work, it seems like a great time to try out some new skills. Any advice would be greatly appreciated, I would like some critiques on my code ( I am not proud of this by any means ) and maybe somebody could suggest good materials I could read. I have learned TONS on my own (outside of the classroom) but I am just lost as to where to go and what the next step is after 'the basics'.

Thanks
Daniel
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: next step in programming? [sample code included]

Post by requinix »

Alright, but you asked for it... (I'm also really bored right now)

Code: Select all

<?php
    // Sets basic checks
    if( isset( $_GET['mode'] ) && isset( $_GET['type'] ) ){
        $mode = $_GET['mode'];
        $type = $_GET['type'];
    }else{
        header( 'Location: ../start.html' );
/* You need an exit(); here. The header() will not stop PHP - it will keep processing the script
   AND the output will be sent to the user; if there were any errors a malicious user could see them
*/
 
    }
   
    require( dbconnection.php );
/* This needs to be a string. You just provided require() with "dbconnectionphp" and PHP just issued
   two warnings (not to mention the file-not-found error)
*/
 
    error_reporting( E_ALL );
/* A) You shouldn't be providing settings like this in scripts
   B) It shouldn't be E_ALL on production servers - users could see every little warning
   C) If, hypothetically, you did put it in a script, put it at the beginning so you don't miss the
      earlier problems
*/
   
        $sqlIcon = "
            SELECT
                iconID,
                iconURL
            FROM
                mapItems_icons
        ";
   
    $resultIcon = mysql_query( $sqlIcon );
    if( !$resultIcon )
        die( mysql_error( $conn ) );
/* Don't do this. If something bad happens the user will see the SQL error message, which typically
   includes parts of the query itself. It gives a malicious user information they shouldn't have.
   Use a generic error page or message, or handle this gracefully
*/
   
    if( $mode == 'edit' ){
        //populates the form fields
       
       
        $sql = "
            SELECT
                m.mapItemID,
                m.name,
                m.address,
                m.url,
                i.iconID
            FROM
                mapItems AS m
                INNER JOIN mapItems_icons AS i
                    ON m.iconID = i.iconID
            ORDER BY
                m.name ASC 
        ";
 
    }else{
        //populates the drop down
        $sql = "
            SELECT
                iconID,
                iconURL
            FROM
                mapItems_icons
        ";
    }
    $result = mysql_query( $sql );
    if( !$result )
        die( mysql_error( $conn ) );
/* Same as above
*/
    $row = mysql_fetch_array( $result, MYSQL_ASSOC );
    $iconid = $row['iconID'];
    echo $iconid;
/* I assume that's temporary, debugging/testing code.
   Many IDEs provide a way of tagging code using comments, such as
   // TODO: remove this when going to production
   and allow you to review all of them from a central location.
*/
?>
<!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>Building Information</title>
    </head>
 
    <body>
 
        <form>
            <fieldset>
                <legend>General Building Information</legend>
                <label for="buildingName">Building Name:</label>
                <input id="buildingName" type="text" size="20" value="<?php if($mode == 'edit'){ echo $row['name']; } ?>" />
                <label for="buildingAddress">Building Address:</label>
                <input id="buildingAddress" type="text" size="20" value="<?php if($mode == 'edit'){ echo $row['address']; } ?>" />
                <label for="buildingImage">Image URL:</label>
                <input for="buildingImage" type="text" size="40" value="<?php if($mode == 'edit'){ echo $row['url']; } ?>" />
<!-- Q: What if one of those $row[] values has a quotation mark in it?
     A: It'll break the HTML.
     Use htmlentities or htmlspecialchars on strings with unpredictable characters - eg, you don't
     need them to escape numbers.
     <?php if ($mode == "edit") echo htmlentities($row["url"]); ?>
-->
            </fieldset>
            <?php if( $type == 'marker' ){ ?>
            <fieldset>
                <legend>Choose a Marker</legend>
                Select a Marker: <select>
            <?php
                //mysql_data_seek($result, 0);
                while( $row = mysql_fetch_array( $resultIcon, MYSQL_ASSOC ) ){
                    $iconID = $row['iconID'];
                    $iconURL = $row['iconURL'];
                   
                    if( $iconID == $iconid ){
                        echo "<option value=\"$iconID\" selected>{$iconURL}</option>\n";
                    }else{
                        echo "<option value=\"$iconID\">{$iconURL}</option>";
                    }
                }
/* What if the SELECT didn't give any rows? A <select> without <option>s is invalid. How about some
   sort of message instead of the <select>?
   Also, same note about htmlentities/htmlspecialchars.
*/
            ?>
                 </select>
            </fieldset>
            <?php } ?>
            <fieldset>
                <legend>Get Coordinates</legend>
                <p>Map will populate here</p>
            </fieldset>
            <br /><br />
            <button>Submit</button>
        </form>
    </body>
</html>
dajohnson1s wrote:Unfortunately, I tend to follow the structure I would for a University assignment, most were very short (and procedural) and could be solved with a single 'main' function or a few secondary functions, never really touching on OO or anything like that.
And PHP encourages that. It's not a problem - that's how PHP was designed to work, and trying to compare it to an OOP/framework-ed environment (like .NET) isn't fair.

If you want a sort of discussion environment, your questions are better suited for the Theory and Design forum.

PS: PHP isn't all that great with the deceptively-complex MVC pattern. And, if you ask me, MVC is hyped way too much.
dajohnson1s
Forum Newbie
Posts: 19
Joined: Sat Nov 15, 2008 12:44 pm

Re: next step in programming? [sample code included]

Post by dajohnson1s »

tasairis,

Thanks, I had no idea about the exit(); function, and I will re-read the rest of your comments. In my defense, this is a 'beginning' page, so I do remove a lot of what you mentioned.

I had read some place that using 'error_reporting( 0 );' is what I should do in a production environment, reason being no error will be sent to the users. Also, even if I am sure that something will be populated, exceptions are definitely a weak point for me.

I also get the impression that MVC is a fad, BUT I have a couple friends that use php (partly why I picked it up over other languages) that say OO php is a game changer, and will definitely change how I look at programming with php. But I will take your advice and post in the mentioned forum as well.

Thanks again.

PS. if there is any other improvements, please feel free to post again.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: next step in programming? [sample code included]

Post by requinix »

dajohnson1s wrote:I had read some place that using 'error_reporting( 0 );' is what I should do in a production environment, reason being no error will be sent to the users.
Well, yes, you should disable errors on production, but you shouldn't need to do it in every file. Apply the setting in one place such as php.ini and you won't have to think about it ever again.
dajohnson1s wrote:I also get the impression that MVC is a fad, BUT I have a couple friends that use php (partly why I picked it up over other languages) that say OO php is a game changer, and will definitely change how I look at programming with php.
Oh yeah, it'll change how people think... Eventually.
MVC is a really powerful concept but (at least with PHP) it's hard to pull off. I, for one, have given up on making a totally MVC framework in exchange for something simple to understand and work with. MVC is something many PHP programmers have a hard time understanding and it's not always worth using.
Maybe in a couple years when OOP is more common will other design patterns become as common in PHP as they are in other languages.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: next step in programming? [sample code included]

Post by Eran »

(at least with PHP) it's hard to pull off
That might have been true 5 years ago, but today every major framework implements the MVC pattern, and they do it in a very similar fashion. Most of the experienced people here use those frequently. We use MVC in all of our projects, and it's hard for me to even imagine doing a major project without MVC separation and structure.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: next step in programming? [sample code included]

Post by requinix »

pytrin wrote:
(at least with PHP) it's hard to pull off
That might have been true 5 years ago, but today every major framework implements the MVC pattern, and they do it in a very similar fashion. Most of the experienced people here use those frequently. We use MVC in all of our projects, and it's hard for me to even imagine doing a major project without MVC separation and structure.
Every MVC implementation I've seen gets close to a "true" MVC structure but doesn't quite reach 100%. Able to do most parts but not some others. Honestly, it's been a few months since I've looked at any, so (a) if anything's changed since then I don't know about it, and (b) I don't remember specific flaws - I've been busy with my own framework and my memories are a bit mixed up.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: next step in programming? [sample code included]

Post by Eran »

Every MVC implementation I've seen gets close to a "true" MVC structure but doesn't quite reach 100%
Could you elaborate on this? what is missing?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: next step in programming? [sample code included]

Post by requinix »

pytrin wrote:
Every MVC implementation I've seen gets close to a "true" MVC structure but doesn't quite reach 100%
Could you elaborate on this? what is missing?
First, like I said it's been a while so my memory's a bit fuzzy on how some stuff worked.

Two issues I remember best:
- a hard time switching out one View for another, like HTML versus RSS
- (relatively) tight coupling between the Model and the Controller - sometimes just importing it right in- while the ones that handled the Model well provided a layer just too abstract and difficult to use effectively

To be fair, my qualifications for MVC are a little stricter than I've heard from others. The way I see it, if all three parts are present,
1. The Model has no coupling to the Controller or View
2. The Controller does not know about the View
3. The View does not know which Controller served it
Just because there's a database, a PHP script, and an HTML template, doesn't mean it's MVC.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: next step in programming? [sample code included]

Post by Weirdan »

tasairis wrote:
dajohnson1s wrote:I had read some place that using 'error_reporting( 0 );' is what I should do in a production environment, reason being no error will be sent to the users.
Well, yes, you should disable errors on production, but you shouldn't need to do it in every file. Apply the setting in one place such as php.ini and you won't have to think about it ever again.
Quite contrary, you should not disable error reporting on production, but you should disable display_errors and enable log_errors. In this way no errors are shown to users, but you get them all in the log file.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: next step in programming? [sample code included]

Post by Eran »

This might belong in a separate thread, but:
Two issues I remember best:
- a hard time switching out one View for another, like HTML versus RSS
- (relatively) tight coupling between the Model and the Controller - sometimes just importing it right in- while the ones that handled the Model well provided a layer just too abstract and difficult to use effectively

To be fair, my qualifications for MVC are a little stricter than I've heard from others. The way I see it, if all three parts are present,
1. The Model has no coupling to the Controller or View
2. The Controller does not know about the View
3. The View does not know which Controller served it
Just because there's a database, a PHP script, and an HTML template, doesn't mean it's MVC.
* There's no problem switching between views, or composing multiple views or formats as output. At least in ZF you have full control on what and how you render output.
* Coupling between controller and model is entirely up to the developer, depending on his competency. There is no built in coupling between controllers and models in the frameworks I've worked with.

Did you try frameworks such as ZF, CakePHP, Symphony?
Post Reply