SitePoint Sponsor

User Tag List

Results 1 to 10 of 10
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question PHP Code Design Insight/Feedback

    I'm relatively new to PHP and as practice I put together a simple website. Currently, it doesn't follow any particular design pattern.

    I'm interested in getting insight/feedback on the following (please respond to any and all):
    1. Is the current layout of the code acceptable?
    2. If yes to question #1, what changes should I make?
    3. If I were to change to the MVC pattern, could I do this without a framework?
    4. Any suggestions/recommendation you may have.

    The pattern of the code is: static html (usually a form), javascript/ajax (retrieves form info, sends to php page), php page performs inserts/updates.

    Following is an example of my code pattern - it is a messaging system:
    HTML:
    Code:
    <body>
    <div id="header"></div>
    
    <div id="contentContainer" class="mainContainer">
    	
    	<div id="banner">
    		<?php $navMenu->display(); ?>
    	</div>
    	<!-- end of #banner -->
    	
    	<div id="msgComposition">
    	<form name="msgForm" id="msgForm" method="post">
    		<fieldset>
    	    	<legend><span>Compose Message</span></legend>
    	        	<ul>
    	            	<li><label for="msgRecipient">To: </label><input type="text" name="msgRecipient" id="msgRecipient" autocomplete="off" size="73"/>
    	                	<label for="msgRecipient" class="error" id="msgRecipientError"></label>
    	                </li>
    	                <li><label for="msgSubject">Subject: </label><input type="text" name="msgSubject" id="msgSubject" size="73"/></li>
    	                <li><label for="msgContent">Message: </label><textarea name="msgContent" id="msgContent" wrap="soft" cols="55" rows="15"></textarea>
    	                    <label for="msgContent" class="error" id="msgContentError"></label>
    	                </li>
    	           </ul>
    	    </fieldset>
    		<fieldset class="submit"><input type="submit" name="msgSend" id="msgSend" value="&raquo; Send"/></fieldset>              	
    	</form>
    	</div>
    	<!-- end of #msgComposition -->
    	
    </div>
    Javascript:
    Code:
    window.onload = function(){
    	
    if (document.getElementById("msgForm")) {
    	document.getElementById("msgForm").onsubmit = function(){
    		var msgRecipient = document.getElementById("msgRecipient").value;
    		var msgSubject = document.getElementById("msgSubject").value;
    		var msgContent = document.getElementById("msgContent").value;
    		
    		if (msgRecipient == "") {
    			document.getElementById("msgRecipientError").innerHTML = "This field is required.";
    			document.getElementById("msgRecipientError").style.display = "inline";
    			document.getElementById("msgRecipient").focus();
    			return false;
    		}
    		
    		if (msgContent == "") {
    			document.getElementById("msgContentError").innerHTML = "This field is required.";
    			document.getElementById("msgContentError").style.display = "inline";
    			document.getElementById("msgContent").focus();
    			return false;
    		}
    		var params = "msgRecipient=" + msgRecipient + "&msgSubject=" + msgSubject + "&msgContent=" + msgContent + "&type=sendMsg";
    		var url = "messaging.php";
    		Ajax.post(params, url, false);
    		
    		if (typeof(Ajax.response) == "undefined") {
    			alert("AJAX Error");
    		}
    		else {
    			var msgNotice = document.createElement("span");
    			msgNotice.setAttribute("id", "msgNotice");
    			msgNotice.style.border = "solid #000066";
    			msgNotice.style.background = "#ffc";
    			msgNotice.style.padding = "5px";
    			msgNotice.innerHTML = "Message Sent";
    			document.getElementById("msgRecipient").value = ""; /** Clear recipient value */
    			document.getElementById("msgSubject").value = ""; /** Clear subject value */
    			document.getElementById("msgContent").value = ""; /** Clear content value */
    			document.getElementById("msgSend").parentNode.insertBefore(msgNotice, document.getElementById("msgSend").nextSibling);
    			//var noticeTimeout = setTimeout( '$("#msgNotice").fadeOut("slow")', 2000 );
    			var noticeTimeout = setTimeout('document.getElementById("msgNotice").parentNode.removeChild(document.getElementById("msgNotice"))', 3500);
    		}
    		return false;
    	}
    }
    }
    PHP:
    PHP Code:
    <?php

    function __autoload($className){
        require_once 
    'classes/'.$className.'.php';
    }
    $dbConn = new DbConnection();
    $format = new StringFormat();

    $connected $dbConn->conn(); // connect to db
    $dbConn->dbSelect(); // select db

    session_start();

    $type $_POST["type"];

    switch(
    $type){
    case 
    "sendMsg":

    $msgParent NULL;
    $msgChild NULL;
    $msgRecipient $_POST["msgRecipient"];
    $msgSender $_SESSION["userId"];
    $msgSubject $_POST["msgSubject"];
    $msgContent $_POST["msgContent"];

    $msgTimestamp date("Y-m-d G:i:s");

    $threadQuery sprintf("INSERT INTO message_thread (threadCreator, threadDate) VALUES (%s, %s)",
    $format->value($msgSender),
    $format->value($msgTimestamp));

    $threadCreation mysql_query($threadQuery$connected) or die("Coud not create thread: " $threadQuery " " mysql_error()); 

    $threadKey mysql_insert_id(); // Save auto-incremented value in threadKey variable

    $contentQuery sprintf("INSERT INTO message_content (threadKey, msgParent, msgChild, msgDate, msgSubject, msgContent) VALUES(%s, %s, %s, %s, %s, %s)",
    $format->value($threadKey),
    $format->value($msgParent),
    $format->value($msgChild),
    $format->value($msgTimestamp),
    $format->value($msgSubject),
    $format->value($msgContent));

    $contentInsert mysql_query($contentQuery$connected) or die("Could not insert into content box: " $contentQuery " " mysql_error());

    if (!
    $contentInsert){
        echo 
    'Message content save error';
        return 
    false;
    }

    $iKey mysql_insert_id();

    $recipientArray explode";" $msgRecipient );
    array_pop($recipientArray);

    foreach ( 
    $recipientArray as $key => $value ){
        
    $recipientSelect "SELECT userId FROM user_information WHERE CONCAT( '( ', memberId, ' )', ' ', firstName, ' ', lastName ) = " "'" $value "'";
        
        
    $queryResult mysql_query($recipientSelect$connected) or die(" Could not match: " $recipientSelect " " mysql_error());
        
    $targetRecipient mysql_fetch_assoc($queryResult);
        
    $recipient[] = $targetRecipient["userId"];

    }


    foreach ( 
    $recipient as $index => $target ){

        
    $inboxQuery sprintf("INSERT INTO message_inbox (msgRecipient, msgSender, msgId) VALUES(%s, %s, %s)",   
        
    $format->value($target),
        
    $format->value($msgSender), 
        
    $format->value($iKey));
        
        
    $inboxInsert mysql_query($inboxQuery$connected) or die(mysql_error());
        
        if (!
    $inboxInsert){
            echo 
    'Inbox error';
            return 
    false;
        }
    }

    $recipientString implode(", " $recipient);

    $outboxQuery sprintf("INSERT INTO message_outbox (msgSender, msgRecipient, msgId) VALUES(%s, %s, %s)",   
    $format->value($msgSender),
    $format->value($recipientString), 
    $format->value($iKey));

    $outboxInsert mysql_query($outboxQuery$connected) or die("Could not insert into outbox: " $outboxQuery " " mysql_error());

    if (!
    $outboxInsert){ 
        echo 
    'Outbox error';
        return 
    false;
    }

    echo 
    'Message sent';

    break;

    case 
    "msgReply":

    $msgParent $_POST["msgParent"];
    $msgChild NULL;
    $replyRecipient $_POST["replyRecipient"];
    $msgSender $_SESSION["userId"];
    $msgSubject $_POST["msgSubject"];
    $msgContent $_POST["msgContent"];

    $msgTimestamp date("Y-m-d h:i:s");

    $threadQuery sprintf("SELECT threadKey FROM message_content WHERE msgId = %s",
    $format->value($msgParent));

    $threadQueryResult mysql_query($threadQuery$connected) or die("Coud not create thread: " $threadQuery " " mysql_error()); 

    $threadInfo mysql_fetch_assoc($threadQueryResult); // Get thread key

    $contentQuery sprintf("INSERT INTO message_content (threadKey, msgParent, msgChild, msgDate, msgSubject, msgContent) VALUES(%s, %s, %s, %s, %s, %s)",
    $format->value($threadInfo["threadKey"]),
    $format->value($msgParent),
    $format->value($msgChild),
    $format->value($msgTimestamp),
    $format->value($msgSubject),
    $format->value($msgContent));

    $contentInsert mysql_query($contentQuery$connected) or die("Could not insert into content box: " $contentQuery " " mysql_error());

    if (!
    $contentInsert){
        echo 
    'Message content save error';
        return 
    false;
    }

    $iKey mysql_insert_id();

    $inboxQuery sprintf("INSERT INTO message_inbox (msgRecipient, msgSender, msgId) VALUES(%s, %s, %s)",
    $format->value($replyRecipient),
    $format->value($msgSender),
    $format->value($iKey));

    $inboxInsert mysql_query($inboxQuery$connected) or die("Could not insert into inbox: " $inboxQuery " " mysql_error());
        
        if (!
    $inboxInsert){
            echo 
    'Inbox error';
            return 
    false;
        }

    $outboxQuery sprintf("INSERT INTO message_outbox (msgSender, msgRecipient, msgId) VALUES(%s, %s, %s)",   
    $format->value($msgSender),
    $format->value($replyRecipient), 
    $format->value($iKey));

    $outboxInsert mysql_query($outboxQuery$connected) or die("Could not insert into outbox: " $outboxQuery " " mysql_error());

    if (!
    $outboxInsert){ 
        echo 
    'Outbox error';
        return 
    false;
    }

    $msgParentUpdateQuery sprintf("UPDATE message_content SET msgChild = %s WHERE msgId = %s",
    $format->value($iKey),
    $format->value($msgParent));

    $msgParentUpdate mysql_query($msgParentUpdateQuery$connected) or die("Could not update msgChild information: " $msgParentUpdateQuery " " mysql_error());

    echo 
    'Message sent';
    break;
    }
    ?>

  2. #2
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    I'm interested in getting insight/feedback on the following (please respond to any and all):
    1. Is the current layout of the code acceptable?
    2. If yes to question #1, what changes should I make?
    3. If I were to change to the MVC pattern, could I do this without a framework?
    4. Any suggestions/recommendation you may have.
    I'm sure you've heard this before, but I just want to emphasise it: It's not black and white. Some techniques are perfectly appropriate for a small application, but would cause chaos in a larger application. Likewise, some techniques would drown a small application in clutter and framework, but are completely essential in a large setting. And there are other axis than small/large as well.

    That aside, I have a couple of observations that you can take or leave.

    Quote Originally Posted by dan06 View Post
    The pattern of the code is: static html (usually a form), javascript/ajax (retrieves form info, sends to php page), php page performs inserts/updates.
    The general interaction pattern for forms should be PRG. In other words, you have a single page (page#1), which displays the form upon GET. It then posts back to itself, and validates the request. If it is valid, the page is redirected a landing page (page#2). If the form is invalid, the page is re-displayed (not redirected), but with error messages and with fields filled in from the post data. As a variation, your page#2 can be the same page, but just with an additional GET parameter.

    You appliance of javascript is imho misuse. You form page should work without javascript. Right now you're setting yourself up for a lot of failures on the edge cases, and to boot a worse user experience. You can add javascript validation of purely syntactic rules (eg. is a field numeric), but they should always be additional to the server side validation. Javascript is better used to enhance the user experience, than to re-implement it. For example, you can show/hide certain fields as the form is filled out.

    Quote Originally Posted by dan06 View Post
    PHP Code:
      <?php $navMenu->display(); ?>
    It's not clear to me how display() generates its code, but be very careful to escape any variables that you embed into html with htmlspecialchars. Also, I would suggest that you return the string and echo it out in the template, rather than within a method.

    Quote Originally Posted by dan06 View Post
    PHP Code:
    $threadQuery sprintf("INSERT INTO message_thread (threadCreator, threadDate) VALUES (%s, %s)",
    $format->value($msgSender),
    $format->value($msgTimestamp));

    $threadCreation mysql_query($threadQuery$connected) or die("Coud not create thread: " $threadQuery " " mysql_error()); 

    $threadKey mysql_insert_id(); // Save auto-incremented value in threadKey variable 
    I assume that $format->value() escapes strings for the query? You could write this code more succinct, with something like:

    PHP Code:
    $result $db->query(
      
    "INSERT INTO message_thread (threadCreator, threadDate) VALUES (?, ?)",
      
    $msgSender,
      
    $msgTimestamp);
    $threadKey $result->lastInsertId(); 
    Note that PDO has been standard with PHP for a while. It has built-in support for prepared statements, that looks quite similar to the above.

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken View Post
    ...It's not black and white. Some techniques are perfectly appropriate for a small application, but would cause chaos in a larger application. Likewise, some techniques would drown a small application in clutter and framework, but are completely essential in a large setting. And there are other axis than small/large as well.
    The part I'm struggling with is determining what is the proper "technique."

    As a way to learn/practice php I put together a web app. The app allows registered users to create a 'recipe book.' Each recipe has descriptions, images, and videos. It also allows users to search for recipes and/or chefs. Lastly, it allow users to buy/sell secret recipes (this module only allow sellers to select starting price and buyers to bid, I haven't done the actual transaction code).

    While the app works (excluding the aforementioned component) as intended, I want to learn how to make the app/code better and 'enterprise' ready - i.e. being manageable, scalable, and handling large user loads like facebook, ebay, yellowpages etc.

    Now knowing the app and my goals how would you recommend I proceed? i.e. Would you recommend that I use a php framework and thus a design pattern?

    Quote Originally Posted by kyberfabrikken View Post
    The general interaction pattern for forms should be PRG... You appliance of javascript is imho misuse...
    I see what you're saying; the reason I used js as I did was to eliminate page re-loads/re-directs.

    Quote Originally Posted by kyberfabrikken View Post
    ...Also, I would suggest that you return the string and echo it out in the template, rather than within a method.
    Thanks for the suggestion, I was curious as to if echoing the html in the method was 'proper.'

    Quote Originally Posted by kyberfabrikken View Post
    Note that PDO has been standard with PHP for a while. It has built-in support for prepared statements, that looks quite similar to the above.
    I found out about PDO & ADObd just last week; I wish I knew about it when I first started learning/practicing...

    Once again, I appreciate you taking the time to share your insight/feedback.

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    Would you recommend that I use a php framework and thus a design pattern?
    "Design patterns" is a dangerous term. They are a kind of recognised strategies, that are often used in the industry. As such, a design pattern does not imply quality. It's just a name for a common way to solve a common problem. Even if you have never heard the phrase before, your code would have many design patterns.

    The point being that you shouldn't strive to add design patterns to your code. They are good for studying, but don't employ them as programming blueprints.

    Frameworks comes with a couple of benefits, but they aren't essential to writing good code. Picking a framework has much more to do with organisation, than with technical merits. I don't say that to scare you away - by all means try a framework out, as you'll probably learn something from it - but don't expect it to solve all the hard problems for you. Manageability and scalability are issues you'll have to address your self. In fact a framework may make these points harder to deal with, because of the abstraction that the introduce.

    But to be clear, in your current situation, a framework can probably be a good help for learning from. I would suggest that you pick one of the less complex solutions. Kohana appears to be a good beginners choice these days.

    Quote Originally Posted by dan06 View Post
    While the app works (excluding the aforementioned component) as intended, I want to learn how to make the app/code better and 'enterprise' ready - i.e. being manageable, scalable, and handling large user loads like facebook, ebay, yellowpages etc.

    Now knowing the app and my goals how would you recommend I proceed?
    Object oriented programming is a very useful paradigm - especially for the model layer of your application. PHP has good support for classical object oriented programming, so I would suggest that you try to use this technique.

    I would also suggest that you decompose your current procedural script somehow. You could start by putting various legs of your switch statement into functions, or perhaps make objects of them. That would make your code more manageable.

    As for performance, I would suggest that you learn how to use a profiler. Xdebug is free and it's pretty easy to use.

  5. #5
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The thing that struck me immediately was that to escape string values in SQL properly, it usually requires the use of the database connection you are going to eventually send it to. So it can figure out what character set its should be using to encode.

    So unless StringFormat does some weird magic behind the scenes, its probably not escaping values entirely properly.

    As already suggested using something like PDO or ADODB, then they take care of it for the general/usual cases.

  6. #6
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken View Post
    It's just a name for a common way to solve a common problem... The point being that you shouldn't strive to add design patterns to your code... don't employ them as programming blueprints.
    I'm a little lost with the above statement; I was thinking of using MVC to make my code more manageable (modular) isn't MVC inherently a blueprint? MVC is interesting because segmenting the code allows for using specialization, i.e. if at some point I wanted to use a web designer to make the app look prettier. But it seems to use MVC a framework is needed (either ZF, Cake, or your own).
    Quote Originally Posted by kyberfabrikken View Post
    Frameworks comes with a couple of benefits, but they aren't essential to writing good code. Picking a framework has much more to do with organisation, than with technical merits... Manageability and scalability are issues you'll have to address your self.
    Do large companies/large projects using php (i.e. youtube, facebook, etc.) use frameworks or do they avoid them?

    From what I understand the biggest benefits of frameworks are (please correct misunderstandings):
    1. Quicker development
    2. Reducing/eliminating redundancy (DRY)
    3. Code organization


    I also thought, that frameworks could help with manageability/scalability. i.e. If the framework uses MVC, code is modularized and logic/design is separated; and if db abstraction is used then it is easier to add or change the number/type of databases.
    Quote Originally Posted by kyberfabrikken View Post
    But to be clear, in your current situation, a framework can probably be a good help for learning from. I would suggest that you pick one of the less complex solutions. Kohana appears to be a good beginners choice these days.
    I started a couple of days ago with Zend Framework and CakePhp, but based on your suggestion I will certainly look into Kohana.
    Quote Originally Posted by kyberfabrikken View Post
    I would also suggest that you decompose your current procedural script somehow. You could start by putting various legs of your switch statement into functions, or perhaps make objects of them. That would make your code more manageable.
    To clarify, do you mean to make a class that replaces the switch or make a class that is instantiated in the switch case?
    Quote Originally Posted by kyberfabrikken View Post
    As for performance, I would suggest that you learn how to use a profiler. Xdebug is free and it's pretty easy to use.
    Thanks for the heads-up; I will definitely be looking into/using this.

  7. #7
    SitePoint Addict webaddictz's Avatar
    Join Date
    Feb 2006
    Location
    Netherlands
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    I'm a little lost with the above statement; I was thinking of using MVC to make my code more manageable (modular) isn't MVC inherently a blueprint? MVC is interesting because segmenting the code allows for using specialization, i.e. if at some point I wanted to use a web designer to make the app look prettier. But it seems to use MVC a framework is needed (either ZF, Cake, or your own).
    It's not needed. As kyberfabrikken already mentioned, frameworks exist to organise your code in a "standard" fashion, but they are not needed to create decent code and you'll still have to write the logic of the application yourself. MVC is a thought, or a mindset, if you will. You can apply it even to simple procedural application, which I always do. It's simply seperating concerns, no matter how or by what means you achieve the seperation.

    Don't let anyone fool you: implementing a design pattern is nothing more than creating a solution for a problem. Using a framework does *not* solve your problems magically, nor does using a design pattern.

    Quote Originally Posted by dan06 View Post
    Do large companies/large projects using php (i.e. youtube, facebook, etc.) use frameworks or do they avoid them?
    I'm not sure about any of them. I know Yahoo! has been using the Symfony framework for some of their applications though.

    Quote Originally Posted by dan06 View Post
    From what I understand the biggest benefits of frameworks are (please correct misunderstandings):
    1. Quicker development
    2. Reducing/eliminating redundancy (DRY)
    3. Code organization
    Although there is something to be said about all of the above points, I think the order of importance is the wrong way around. I'd say the organisation of the code is way more important than speeding up the development process. When your code is organised cleanly, the development of code will be faster.

    Of course, (some) frameworks have abstraction layers to do complicated things with a simple API. Instead of learning the ins and outs of the matter at hand, it will simplify the process by giving you a clear and consise way to do the complicated stuff.

    DRY is a concept which isn't really enforced by a framework. I've seen plenty of applications were built on Zend Framework or Symfony which had a shitload of duplicate code in them. The one who's writing the code is responsible for not repeating the code, not the framework.

    I'd say that the prime benefit of using a framework is that your code will become more obvious, because it's always written in a standard way (e.g. code organisation). The second benefit would be that using a framework, you can simplify tedious work because the framework has hidden complex implementation behind a clear interface (such as sending an e-mail through an SMTP server). Those two benefits will result in the fact that you can work a bit faster, but I really see that as a *result* of the structure and libraries, rather than a goal.

    Quote Originally Posted by dan06 View Post
    I also thought, that frameworks could help with manageability/scalability. i.e. If the framework uses MVC, code is modularized and logic/design is separated; and if db abstraction is used then it is easier to add or change the number/type of databases.
    Then you were mistaken. Manageability could be improved, again because of the fact that your code is organised in a standard way. The manageability is, however, dependant on you: if you write bad code on top of the framework, manageability is gone.

    Again: a framework is no silver bullet. It provides API's and a consistent way of working, but it won't write the application for you. It won't modularise your code. It (definitely) won't make the application scalable. It won't per se make it easier to change the number of databases, or the database vendor. Those thing are all up to you and your code.

    Quote Originally Posted by dan06 View Post
    I started a couple of days ago with Zend Framework and CakePhp, but based on your suggestion I will certainly look into Kohana.
    You should certainly look into them. Really. There's tons of code in frameworks that I use on a daily basis, simply because it's easier to use an abstraction than to write a new implementation. Kohana is supposed to be easy (or easier) to grasp than Zend Framework or CakePHP. I myself, like everyone, have my own set of code that I use on projects frequently.
    Yes, I blog, too.

  8. #8
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by webaddictz View Post
    It's not needed...It's simply seperating concerns, no matter how or by what means you achieve the seperation.
    From the reading I've done and the understanding I've gotten about MVC there is a specific flow of interaction between the 3 components
    For example:
    1. View presents a form to user
    2. User interacts with form and the interaction is captured by controller and transferred to model
    3. Model retrieves info from db and returns data to controller
    4. Controller selects view and passes data (which it received from the model) to selected view
    5. View displays data received from controller

    How do you do the above without either a pre-made or self-made framework?

    Quote Originally Posted by webaddictz View Post
    You should certainly look into them. Really. There's tons of code in frameworks that I use on a daily basis, simply because it's easier to use an abstraction than to write a new implementation. Kohana is supposed to be easy (or easier) to grasp than Zend Framework or CakePHP. I myself, like everyone, have my own set of code that I use on projects frequently.
    For me, it's been so far so good with Zend Framework. What do you guys think of symfony? I know it's subjective but which frameworks, if any, do you like?

    Lastly, if you were creating the recipe app (see my second post on Aug. 12th), how would you do/approach it?

    Thanks.

  9. #9
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    How do you do the above without either a pre-made or self-made framework?
    You could, quite simply, use a page controller like so...
    PHP Code:
    <?php
    //viewPost.php #controller
    $post PostGateway::FindById($_GET['id']); #model
    echo $post->render(); #view
    ?>
    This allows you to utilise MVC without a full blown framework, you'll have to use a little imagination but...

    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  10. #10
    SitePoint Addict webaddictz's Avatar
    Join Date
    Feb 2006
    Location
    Netherlands
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    From the reading I've done and the understanding I've gotten about MVC there is a specific flow of interaction between the 3 components
    Though there are a few different opinions on how the communication between the layers should work, most people would agree on the flow you've described. It's also exactly the flow that the Zend Framework seems to support. The flow, however, is *not* the definition of the design pattern Model View Controller: that's simply separating the bussiness logic, presentation logic and application logic, no matter how you are to achieve that separation.

    I think the problems of Model View Controller come from the fact that everyone is talking about the implementation, whereas a Design Pattern should not be about implementation, more about the problem and how it's generally solved. If there are a few people giving different implementations, people not familiar with the pattern will become confused. Or, at least, that's what I think.

    Quote Originally Posted by dan06 View Post
    How do you do the above without either a pre-made or self-made framework?
    Well, I always write the Domain Model (the bussinesslogic) in objects, simply because it's easier to have that abstraction and readability. In the rest, a simple procedural script will do for handling the request, and rendering the view is simply rendering a template. So you do not need a framework to achieve the separation of the concerns, you can do it yourself, no problems.

    On the other hand, having an object oriented framework that can map requests to controllers and supports complex views can make your life easier. I'm just saying: MVC is a theory (and a nice one at that), not an implementation.

    Quote Originally Posted by dan06 View Post
    For me, it's been so far so good with Zend Framework. What do you guys think of symfony? I know it's subjective but which frameworks, if any, do you like?
    I like Symfony for it's ability to generate models, controllers and views automatically. There's just less work to be done. I like some of the components in Zend Framework, because of the abstraction of complex implementations in a simpler API as I've mentioned before.

    Quote Originally Posted by dan06 View Post
    Lastly, if you were creating the recipe app (see my second post on Aug. 12th), how would you do/approach it?
    Start extracting the model, then use a framework for the controllers (I like to use Kyberfabrikken's Konstrukt for this), and get the presentation in templates. Start splitting the concerns, that's it
    Yes, I blog, too.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •