SitePoint Sponsor

User Tag List

Results 1 to 24 of 24
  1. #1
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Comments Please ?

    Okay folks, attempting to understand MVC I have come up with the follow.

    It's not fully complete as I'd like to see what other members think first - is the layering correct for example ?

    PHP Code:
    <?php
     
    include('includes/dao.class.php');
     include(
    'includes/transform.class.php');
     
     
    $Db = & new MYSQLAccess('temp''''''');
     
     
    # create new instance of class Controller
     
    $Cntrl = & new Controller($Db);
     
    # dump $_GET and $_POST to class variables
     
    $Cntrl -> GrabResponse();
     
    # execute a command passed from $_GET or $_POST, or default if none
     
    $Cntrl -> ExecCommand();
     
     class 
    ViewUserModelLyr {
      var 
    $da;
      var 
    $view;
      
      
    /** constructor
      */
      
    function ViewUserModelLyr(& $da) { 
       
    # object referred belongs to mysqlaccess class instance
       
    $this -> da = & $da;
       
    # xml document (template) required by default (may be one or more per Model)
       
    $this -> view = & new TransformFile('view-users.xml');
       
       
    # testing...
       
    echo($this -> view -> Fetch());
       
       
    # ...
       # would then apply transformation after i've put in any dynamic data
       # ... transformation would be via class transformfile btw from this point
      
    }
     }
     
     class 
    TransformFile {
      var 
    $file;
      
      
    /** constructor
      */
      
    function TransformFile($file) {
       
    # ...
       # create new instance of transoformxml class
       # ...
       # define template directory
       # ...
       # define xsl-t transformation file
       # ... before following below
       
       # xml document (template) to use
       // $this -> file = & $file;
       
    $this -> file 'Some sample text instead of fetched xml well formed string.';
      }
      
      function & 
    Fetch() {
       
    # fetch well formed xml string
       
    return $this -> file;
      }
     }
     
     class 
    Controller {
      var 
    $da;
      var 
    $cmd;
      var 
    $keys = array();
      var 
    $values = array();
      
      
    /** constructor
      */
      
    function Controller(& $da) {
       
    # refer to database connection
       
    $this -> da = & $da;
       
    # command from user to follow through; default if none
       
    $this -> cmd '';
      }
      
      function 
    ExecCommand() {
       if(
    $this -> cmd != '') {
        return new 
    $this -> cmd($this -> da);
       }
       else {
        
    # would execute a default command from here
        
    return false;
       }
      }
      
      
    /** class method
      */
      
    function GrabResponse() {
       if(
    $_GET) {
        while(list(
    $key$val) = each($_GET)) {
         
    #
         
    $val trim($val);
         
    $val htmlspecialchars($valENT_QUOTES);
         
    $val stripslashes($val);
         
         
    # is there a command ? if so put to class variable
         
    if(strtolower($key) == (string) 'cmd') {
          
    # append an identifier (ie Model layer) to executable command passed
          
    $this -> cmd $val 'ModelLyr';
         }
         
         
    $this -> keys[] = $key;
         
    $this -> values[] = $val;
        } 
    # end while loop
       
    }
       
       if(
    $_POST) {
        
    # look at any FORM submits
        
    while(list($key$val) = each($_POST)) {
         
    #
         
    $val trim($val);
         
    $val htmlspecialchars($valENT_QUOTES);
         
    $val stripslashes($val);
         
         
    # look for a command from here as well
         
    if(strtolower($key) == (string) 'cmd' && $this -> cmd == (string) '') {
          
    # a $_GET response has a higher priority over any $_POST command
          
    $this -> cmd $val 'ModelLyr';
         }
         
         
    $this -> keys[] = $key;
         
    $this -> values[] = $val;
        } 
       }
      }
     }
     
    ?>
    Am I on the right road here ? Any comments & views and/or pointing in right direction are welcomed

  2. #2
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No one ? Sure someone has something to add ?

    ...

  3. #3
    ********* Wizard silver trophy Cam's Avatar
    Join Date
    Aug 2002
    Location
    Burpengary, Australia
    Posts
    4,495
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    I have no experience with MVC but if I did I'd comment

  4. #4
    As the name suggests... trickie's Avatar
    Join Date
    Jul 2002
    Location
    Melbourne, Australia
    Posts
    678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How come you are storing the key/value pairs of $_GET and $_POST in the controller object?

    I'd say the layering is ok. You seperate out the presentation of content. And you seperate the creation and execution of cmds. I just reckon that the way commands are triggered is by identification. So you need to have a way to handle different types of requests. Encapsulate the cmd identification within a strategy pattern, and you will be able to handle requests from more than $_GET and $_POST vars.

    My 2 cents.

    Last edited by trickie; May 19, 2003 at 06:46.

  5. #5
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks I was thinking about this myself yersterday, since as it is I have no means of putting the $_GET and $_POST variables/values to the Model it's self unless I refer the Controller to the Model which I don't think is the way to do it.

    Like for Form Validation this is going to be a major headache using the way everything is at the moment....

    ... I'm looking at some stuff by HarryF based on an Event Handler to see how he's done it and maybe base my efforts around this ?

    Anyway, I've also had a rethink about how the Model/View work together and what I've done now is to return the xml string from the Model once it has finished and then the View can take this result and then transform it as required.

    This way if I decide later, I could create another view altogether to use HTML templates directly; instead of using xml and xsl-t, since the model would only return the HTML template string with the custom tags removed with PHP inserted data if you follow ?

    Okay, so I have to change the way I access/store the $_GET and $_POST variables in such a way that the Model can also use them.

    I'm now off to phppatterns.com....

    Thanks folks, and DJ P@ckman at least you posted a comment

  6. #6
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    Thanks I was thinking about this myself yersterday, since as it is I have no means of putting the $_GET and $_POST variables/values to the Model it's self unless I refer the Controller to the Model which I don't think is the way to do it.
    The Model doesn't (and shouldn't) care about the $_GET and $_POST data -- that's the Controller's responsibility. The Controller looks at the input and decides which Models objects to instantiate based on that input.

    Quote Originally Posted by Dr Livingston
    Anyway, I've also had a rethink about how the Model/View work together and what I've done now is to return the xml string from the Model once it has finished and then the View can take this result and then transform it as required.
    The Model should probably not be producing XML. Anything that has anything to do with presentation should be handled by the Controller and/or View. The most important part of MVC is breaking the M from the VC (separating the model from the presentation) -- in fact, when MVC was first developed, the View and the Controller were not separated at all. In your case, the Controller should probably generate the XML, based on the Model objects that it instantiates, and hand it off to the View.

    I have to admit that I didn't read the rest of this thread very carefully, so I'm speaking in general terms, but hopefully it makes sense and applies to what you're working on.

    -geoff

  7. #7
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yip - first part is exactly the way I had looked at, although with the Model I was refering to how you'd handle form validations etc.

    The posted script I had the controller put the $_GET/$_POST to an array as you've stated ?

    But much thanks as you've now cleared this up for me... finally I have something to work with

    Now....

    The Model that I was 'about' to do would parse through the xml document looking for custom tags (ie <import />) and then would replace this with dynamic content generated by PHP - ie the Model if you follow ?

    Okay, so from what you said in the next paragraph (looking again....) that the Controller should put objects from Model to the View ?

    But for example, the Model would only return one object - the completely parsed xml document as a string; the transformation class has numerous child classes each which do a specific task, ie create a dynamic link, create a table row/cell format etc etc.

    These couldn't be accessed from the Model if the parent transformation class was created by Controller directly.

    If I could be more clearer, if I have to have functionality for example, to view all users, the logic for this would be done by the Model, no ? Ie database queries, checking user permissions etc.

    The way I looked at it was then create the content based on this logic, and return the xml string back to Controller which would then put it to the View.

    Pheww... Yes, complicated I'd say

    Thanks all the same, and I'll see what I can do although I'd very much like the Model to do the generation of the dynamic content it's self and not the Controller....


  8. #8
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, looking at some thing I have from the Sun website, only revelant parts to codezilla's post btw:

    CONTROLLER
    * Maps user actions (ie $_GET/$_POST) to model updates
    * Selects view for response (ie my xml string ?)

    MODEL
    * Respond to state queries (ie A Command - $_GET['cmd'] = viewuser) passed by CONTROLLER
    * Exposes app functionality (ie logic/business layer ?)

    VIEW
    * Renders the model (ie does the actual transformation of xml string to xhtml)
    * Sends user gestures to CONTROLLER (ie via URL query string/$_POSTs)

    Looking at your post codezilla, and then again looking at, I'd maybe begin to think I was on the right track ?

    It's the View (in my case) that does the 'rendering' (tranformation) of the xHTML, not the Model which only generates the xml - a point I think I could have made a lot clearer....

    Comments please ?

  9. #9
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I didn't look at your code very carefully, so I wasn't sure where the XML was coming from or going to. In fact, I'm still not sure. What is the *overall* purpose of your example code? To display information about a user?

  10. #10
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, yes

    The Model Layer would use a Dao (see HarryF's work at phppatterns.com) for user queries etc and then complete the xml document by replacing tags with the generated content.

    Then the xml well formed string once complete would be passed back to the Controller for View to use - although the posted script does not show this since it is old script

    I'm working on the new script based on the fact that I'm passing back to the Controller this xml string; and not having the Model (as described by the posted script) making the transformation as well (as generating the content).

    Ahem....

    I think I proberly would need to post some more script, but the class that deals with the events ($_GET and $_POST) I was thinking that the Controller would encapsulate this class ?

    What do you think... or would it be better for the Controller to actually create the class instance to grab events...

    Ummm.... It's still a struggle understanding what goes where

  11. #11
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's getting late over here in Scotland (about 8pm) so I post more script tomorrow ?

  12. #12
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sounds good, I'm working on a reply, but I'm horribly slow (which is why I usually don't post much). Enjoy your evening!

  13. #13
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm still not clear on the XML part. Is the XML only used by the View to generate XHTML (via XSLT)? What XML is the Model generating and why? I'm not in the XML camp, so maybe I'm looking at it from the wrong angle.

    Speaking of not being clear (or maybe just dense), I never got the whole Event thing. To me, an EventHandler sounds like the exact same thing as a Controller. Here's how I break it down the whole process (kind of):

    1) User provides input (form submission, url parameters, etc.).
    Example: http://example.com/users/?id=100

    2) The application receives the request and instantiates all necessary objects to handle the request and produce a response.

    3) The Controller looks at the query data and instantiates the appropriate Model object(s) based on that data.

    4) The Controller hands the Model(s) off to the View.

    5) The View outputs a response.

    Here's a simplified version of the code that may create more questions that it answers:

    /users/index.php:
    PHP Code:
    // The page itself is essentially the 
    // Controller
    require_once('UserDao.class.php');
    require_once(
    'UserView.class.php');

    // Model
    $dao =& new UserDao('mysql://my_user:my_pass@localhost/my_db')
    $user =& $dao->findForId($_REQUEST['id']);

    // View
    $view =& new UserView($user);
    $view->print(); 
    Obviously the bulk of the work is done in the Dao and the View classes. The $view object would use view-users.xml (from your example) and the $user object passed to it (in my example) to generate the view. As long as your User class has the appropriate methods (getName(), getUserId(), etc.), the View should be able to generate the response and do all the XML/XSLT/XHTML acrobatics. Be sure to factor out the common functionality into a View super class.

    Does this help at all?

  14. #14
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, here is a rough idea of what I have in mind at the moment.

    PHP Code:
    require('includes/dao.class.php');
     require(
    'includes/transform.class.php');
     
     
    # Layer : Controller
     
     # new instance of MYSQLAccess class
     
    $Sql = & new MYSQLAccess('temp''''''');
     
    # new instance of Controller class
     
    $Cntr = & new Controller;
     
    # register events 
     
    $Cntr -> RegisterEvents();
     
    # execute Model Layer based on a command
      # could proberly do with putting keys and values as one class method
     
    $Cntr -> Execute(& $Sql);
     
    # now transform xml well formed string via View Layer
      # but this new instance should be done from Controller Layer ? ...
     
    $View = new SablotronXSLT;
     
    $View -> SetXmlDir('');
     
    $View -> SetXslFile('transform.xsl');
     
    $View -> Transform($Cntr -> GetXmlString());
     
     
    # all done now
     
     
    class ViewUserModelLyr 
      
    # would begin new instance of Transform class from here
      # to transform an xml document (template) by inserting dynamic
      # content into template replacing given tags ie <import />
      #
      # then return well formed xml string back to Controller Layer for use
      # by View Layer
      
      
    function GetTextOk() { return $this -> text; }
      function 
    ViewUserModelLyr() { $this -> text =  'Hello World !! Sample Text Hee Hee :)'; }
     }
     
     class 
    Controller {
      var 
    $da;
      var 
    $xml;
      var 
    $keys;
      var 
    $values;
      var 
    $command;
      
      
    /** constructor
      */
      
    function Controller() {
       
    # NULL
       
    $this -> command '';
      }
      
      function 
    GetXmlString() {
       return 
    $this -> xml -> GetTextOk();
      }
      
      function 
    GetKeys() {
       return 
    $this -> keys;
      }
      
      function 
    GetValues() {
       return 
    $this -> values;
      }
      
      function 
    GetCommand() {
       return 
    $this -> command;
      }
      
      function 
    Execute(& $da) {
       if(
    class_exists($this -> command) && $this -> command != (string) '') {
        
    # pass along events as to be used for Form validation if required ?
        
    $this -> xml = new $this -> command($this -> da$this -> GetKeys$this -> GetValues);
       }
      }
      
      function 
    RegisterEvents() {
       if(
    $_POST) {
        while(list(
    $key$val) = each($_POST)) {
         
    #
         
    $val trim($val);
         
    $val htmlspecialchars($valENT_QUOTES);
         
    $val stripslashes($val);
         
         
    # is there a command ? if so put to class variable
         
    if(strtolower($key) == (string) 'cmd') {
          
    # append an identifier (ie Model layer) to executable command passed
          
    $this -> command $val 'ModelLyr';
         }
         
         
    $this -> keys[] = $key;
         
    $this -> values[] = $val;
        } 
    # end WHILE
       
    }
      
       if(
    $_GET) {
        
    # look at any URL query string
        
    while(list($key$val) = each($_GET)) {
         
    #
         
    $val trim($val);
         
    $val htmlspecialchars($valENT_QUOTES);
         
    $val stripslashes($val);
          
         
    # look for a command from here as well
         
    if(strtolower($key) == (string) 'cmd' && $this -> command == (string) '') {
          
    # a $_POST event has a higher priority over any $_GET event
          
    $this -> command $val 'ModelLyr';
         } 
    # end IF
          
         
    $this -> keys[] = $key;
         
    $this -> values[] = $val;
        } 
    # end WHILE
       
    # end IF
      
    # end class method
     

    Now....

    The class ViewUserModelLyr is the MODEL and it's this class which would take the xml document - a template - and parse the tags (ie <import />) and replace said tags with data generated by this classes own logic.

    At the end, it returns the parsed xml document back to the CONTROLLER as a string (ie GetXmlString() class method).

    CONTROLLER then gets the xml string and then the VIEW transforms this xml well formed string to xHTML via a stylesheet.

    Hope this helps, although thanks for your help; more so for your last reply which I'm going to study a bit more tomorrow.

    Cheers

  15. #15
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In fact I might be confusing you some more....

    class ViewUserModelLyr {
    # would begin new instance of Transform class from here
    # to transform an xml document (template) by inserting dynamic
    # content into template replacing given tags ie <import />
    #
    When I mean 'Transform' I mean transform the template it's self and not actually tranform the xml document to xHTML

    Hope that explains the comments within the class ViewUserModelLyr { ... }


  16. #16
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    UK
    Posts
    105
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PMFBI

    My understanding of the MVC methodology is that the Model contains, well, the models, by this I mean it contains your classes and functions. The view is the class or whatever which takes the output template, parses it and inserts the resultant data from the controller functions. The controller joins the model and the view together, analysing and processing user input, doing the donkey work, the glue as it were.

  17. #17
    As the name suggests... trickie's Avatar
    Join Date
    Jul 2002
    Location
    Melbourne, Australia
    Posts
    678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Model - Data model, that is the structure of the sructures that contain application information (Data)

    Controller - executes user requests. Based on the request, it gets information from the model and arranges it together.

    View - is how the data resulting from a request (or event or whatever) is represented in the users eyes. This can be the result of a XSLT tranformation of the XML produced by the controller, or maybe just a tabular dump of a DB table.


    Layman's terms. Nearly. Probably not.

  18. #18
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Trickie, like I said above I'm not in the XML camp --so maybe I just don't get it, but why would the Controller be producing XML if it is only used to generate a View?

  19. #19
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I shouldn't think that the CONTROLLER it's self would generate the XML string either

    The view is the class or whatever which takes the output template, parses it and inserts the resultant data from the controller functions.
    Torrent - I don't think the VIEW would be used to insert any data of any kind at all ?

    The VIEW is only concerned with displaying the page based on user actions.

    .... take a breather ....

    Anyway, it looks like everyone - myself included - has their own interpertation of MVC

    Going by what script I've now posted late yersterday, I'm going to leave the VIEW outside the CONTROLLER for the moment and see how things go from there.

    At the end of the day, for everyone, it's down to what you want to do with the MVC I suppose ?

  20. #20
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    UK
    Posts
    105
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I meant more that the Controller populates the variables which are then used in the view. Something somewhere has to then parse the html and insert the contents of those vars in the correct places.

    I liken this to using the patTemplate() class, which I did recently. patTemplate caters only for separating the view from the controller. It does this by allowing you to place special tags within the HTML, populating the vars those tags correspond to, in the controller, and then parsing the HTML file and constructing the result. For example:
    PHP Code:
    $template = new patTemplate()
    $template->setBaseDir('html');
    $template->readTemplatesFromFile('foobar.html');

    $template->addVar('foobar''TITLE''My Title');
    $template->addVar('foobar''STYLESHEET''foo.css');

    $template->displayParsedTemplate('foobar'); 
    The HTML file might contain the following
    Code:
    <title>{TITLE}</title>
    <link rel="stylesheet" type="text/css" media="all" href="/css/{STYLESHEET}" />
    .... take a breather ....

    I know one thing's for sure. I like to view models (the female kind), as for the controller, well, that's the wife

  21. #21
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


    I see your point, though that is a 2 tier archetechture; you miss out the MODEL layer.

    In your script posted above the CONTROLLER has to import the data to the template; this should actually be the task of the MODEL from what I've read at Sun and IBM....

    That's the theory side - now putting it to a working framework properly is why I've started this discussion.

    Yes, I had to take a breather (all so known as a break here in Scotland ) as my head is starting to hurt

  22. #22
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Dr. Livingston -- I finally took a closer look at your code and I think you're mis-understanding MVC.

    In MVC, the MODEL is one or more objects that represent the core data and behaviour in an application (just like Trickie wrote). In your example, you should have one Model class and it should be called User. [One good way to figure out what your model classes should be is write down a description what your application does, then look at the nouns and you'll soon find all your model classes.] Specifically, your User class should have all relevant User data (e.g. username, firstname, lastname, lastlogin, etc.) which will be the properites for the User class, and all relevant behaviors (e.g. login, logout, etc.) which will be the methods for the User class [notice that these are all verbs].

    The CONTROLLER's job is to look at the user input (found in $_GET/$_POST) and figure out what Model objects to instantiate and which View to output. The Controller then hands the Model objects to the View. In your example, the controller should instantiate (via a DAO) a User object (the model) based on the supplied user input (possibly $_GET['user_id']), then instantiate the proper View object and pass it the User object.

    The VIEW receives the Model objects from the Controller and extracts the information it needs in order to generate the proper output. In your example, the View object would receive a User object and get the data it needs ($user->getUsername(), $user->getFirstName(), $user->getLastLogin()), then insert that data into a template. Currently you're doing this in your Controller and ViewUserModelLyr (which looks more like a Controller/View than a Model). Any logic used to format a view (known as presentation logic -- not to be confused with business logic, which belongs in the Model) should also be part of the View. In otherwords, XML/XSLT/XHTML functionality should happen in the View or a ViewHelper.

    It looks like you're also using something called a FrontController, which is a special kind of Controller that handles all requests for a web site. I'm guessing this is the case because your Controller class is looking for user input with the key 'cmd'. It takes the value of this data and generates a command class (ViewUserModelLyr). In FrontController, the Controller functionality is spread out by a couple classes -- but different people have different names for these classes so it's hard to give a definitive explanation.

    Here's an exanded version of my previous example code:
    PHP Code:
    // Handler portion of FrontController
    $cmd $_REQUEST['cmd'];
    if (
    $cmd && is_file($cmd 'Command.class.php'))
    {
        require_once(
    $cmd 'Command.class.php');
        
    $command =& new $cmd();
        
    $command->process();

    PHP Code:
    // Command portion of FrontController
    require_once('DataSource.class.php'); 
    require_once(
    'UserDao.class.php'); 
    require_once(
    'UserView.class.php'); 

    class 
    ViewUserCommand()
    {

        function 
    ViewUserCommand()
        {
        }
        
        function 
    process()
        {
            
    $ds =& new DataSource(
                
    'mysql://my_user:my_pass@localhost/my_db');
            
    $dao =& new UserDao($ds->getConnection());
            
    $user =& $dao->findForId($_GET['user_id']); 
            
    $view =& new UserView($user); 
            
    $view->print(); 
        }

    PHP Code:
    // DAO
    require_once('User.class.php');

    class 
    UserDao
    {
        var 
    $db;

        function 
    UserDao(&$db)
        {
            
    $this->db =& $db;
        }
        
        function &
    findForId($id)
        {
            
    $rs =& $this->db->execute(
                
    "SELECT * FROM user WHERE id = $id");
            
    $rs->next();
            return new 
    User(
                
    $rs->get('username'),
                
    $rs->get('name'),
                
    $rs->get('lastlogin'));
        }

    PHP Code:
    // Model
    class User
    {
        var 
    $lastLogin;
        var 
    $name;
        var 
    $username;

        function 
    User($username$name$lastLogin)
        {
            
    $this->lastlogin $lastLogin;
            
    $this->name $name;
            
    $this->username $username;
        }
        
        function 
    getLastLogin() { return $this->lastLogin; }
        function 
    getName() { return $this->name; }
        function 
    getUsername() { return $this->username; }
        function 
    login() { //login user }
        
    function logout() { //logout user }

    PHP Code:
    // View
    require_once('Transform.class.php');

    class 
    UserView
    {
        var 
    $user;

        function 
    UserView(&$user)
        {
            
    $this->user =& $user;
        }
        
        function print()
        {
            
    // extract data from $this->user and put values in template file
            // ...
            // ...
            // ...

            
    $xslt =& new SablotronXSLT();
            
    $xslt->SetXmlDir('');
            
    $xslt->SetXslFile('transform.xsl');
            
    $this->xslt->Transform();
        }

    There's all sorts of improvements that can be made with this, but the example is as basic as I can make it and still include all the important stuff.

    Quote Originally Posted by Dr Livingston
    Anyway, it looks like everyone - myself included - has their own interpertation of MVC
    I think this is because most people simply don't understand MVC -- there's lots of misinformation out there. Hopefully, I'm not one of those people who don't truly understand it and is spreading more misinformation. I'm pretty confident that I have a fair grasp of MVC -- I just hope I can help explain it.

    Here are some great resources for further reading:

    http://www.martinfowler.com/books.html#eaa
    http://java.sun.com/blueprints/corej...rns/index.html
    http://java.sun.com/blueprints/patterns/catalog.html

  23. #23
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    I see your point, though that is a 2 tier archetechture; you miss out the MODEL layer.

    In your script posted above the CONTROLLER has to import the data to the template; this should actually be the task of the MODEL from what I've read at Sun and IBM....
    Assuming you're addressing my post from yestereday, look again. The Model is there -- it's the $user object. Remember the Model is only a representation of the core business data and behaviour. Basically, the data in your database is the Model -- or, more precisely, your Model objects are stored ("persisted") in your database. The Model should have absolutely no knowledge of user requests (input) or application response (output) -- which is handled by the View and Controller (i.e. the presentation layer).

    The Controller creates the appropriate Model objects and gives them to the View to create output. DAOs help create Model objects by abstracting out the database interactions.

    So a DAO imports data from a database to a Model object, but the View imports (extracts) data from the Model objects and inserts them in the template to generate the response (output).

    Suppose you were working on a forum application. Some of your Model objects would be: Forum, Thread, Post, User, etc. The Controllers would be the PHP pages. For example, the page used to create a new Topic (the Controller), would be a form (like the one I'm typing on write now) that, when submitted, will create a new Post object (the Model), then persist than object by handing it off to a DAO which would do an INSERT. The Controller could then display a message indicating that the Post was successfully added (the View).

  24. #24
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Torrent - Oppss...

    Codezilla - Thanks for helping me out; your post (2nd last) has cleared up a lot for me - I have a rough idea of what your examples are doing.

    I've just gotten it wrong again (what ? ) which is not the first time, though yes, this MVC is a bit complicated for me to fully understand since I kind of flunked my HNC

    As for my HND - don't ask Okay, I did look at some stuff at Sun - also some stuff at (spit) MSDN. I understand the theory of things I suppost; but it's those diagrams and UMLs that are getting me I think - not being fully educated you see ?



    Thanks folks, I'll have another study of your examples codezilla and cheers in the meantime.


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
  •