SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 48

Hybrid View

  1. #1
    SitePoint Enthusiast CamelToe's Avatar
    Join Date
    May 2003
    Location
    Canada
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Separate Logic / Presentation without Templates

    Hi,

    I do not in any way intend for this thread to be a rant of 'To Use' or 'Not to Use' templates OR XLST for that matter. I have already made up my mind, and I feel that PHP in itself is a worthy template engine. (FYI, For the XSLT Fans, The Server I have does not have Sablotron compiled - php v. 4.1.?)

    Being that, I would like to Separate my Application Logic from my Presentation Layer.

    I have gone through some threads on this forum (only forum I'm aware of with any real information on this topic (PHP based)). There were a few very interesting threads that I have printed / saved and studied.

    Anyways, I would really like to have a Class for instance a Books Class that would possible extend a Page Class?

    Here is what I have: (Using Eclipse):

    PHP Code:
    // Require The Application Data
    require_once("application/init.php");

    $db =& new MyDatabase(DB_DATABASEDB_SERVER);
    $db->connect(DB_USERDB_PASS);

    $sql ="SELECT * FROM test";    

    $resultSet $db->query(& $sql);
    $iterator =& new QueryIterator($resultSet);

    while(
    $row $iterator->getCurrent())  {
        
        echo 
    "<p>Book Title: <b>" $row['BookTitle'] . "</b><br><br>";
        
    $iterator->next(); 


    $db->disconnect();

    echo 
    "<b><p align=center>This is the End</b></p>"
    As you can see, I have HTML in my Logic.
    I just did this to make sure I got the freakin thing working. It was pretty easy enough.

    How would I go about separating this??? OOP of course.

    Please Note: I have looked in DAO and MVC. Are there other alternatives???

    Thanks!!!!
    And Sorry for the ignorance.

  2. #2
    SitePoint Enthusiast CamelToe's Avatar
    Join Date
    May 2003
    Location
    Canada
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was looking more closely at the Eclipse API a short while ago, would this be an example??
    PHP Code:
       class BookAuthorsPrinter extends RowLoopManipulator
       
    {
           function 
    BookAuthorsPrinter()
           {
               
    $this->RowLoopManipulator();
               
    $watcher =& $this->addWatcher('author');
               
    $watcher->register('author');
           }

           function 
    author(&$row$index)
           {
               echo 
    "<b>${row['author']}</b>:<br>\n";
           }

           function 
    current(&$row$index)
           {
               
    parent::current($row$index);
               echo 
    " - ${row['title']}<br>\n";
           }
       }

       
    $result $database->query(
           
    'SELECT author.name AS author, book.title AS title
            FROM author, book
            WHERE book.author_id = author.id
            GROUP BY author'
       
    );
       
    Loop::run(new QueryIterator($result), new BookAuthorsPrinter); 

  3. #3
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry I can't help as at the moment I've been learning MVC myself although I'm still learning more about it but from my experience it is a difficult subject to properly understand

    You are correct though about using a Dao though this it's self is only the Data Access Layer; you have the View, Model and Controller Layers as well to design and implement... completely seperate abviously though I point out in the view of scripting and not design

    But I would seriously think about using some sort of Templates; else you've no way of implementing the View except for raw HTML - a problem when you begin to put your data in there ?

    Me ? I use an XML template....

    Here is some links I have from Java; a good place to start to learn MVC; Also look at phppatterns.com as HarryF cover's some stuff on PHP;

    http://java.sun.com/docs/books/tutor....html#concepts
    http://st-www.cs.uiuc.edu/users/smarch/st-docs/mvc.html
    http://ootips.org/mvc-pattern.html
    http://java.sun.com/blueprints/guide.../DEA2eTOC.html

  4. #4
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Few thoughts;

    First you have to ask yourself "what is presentation logic?". For me it's not just HTML in a PHP string but also the code responsible for generating it.

    In your example that means;

    PHP Code:
    while($row $iterator->getCurrent())  {
        
        echo 
    "<p>Book Title: <b>" $row['BookTitle'] . "</b><br><br>";
        
    $iterator->next();
    }
    echo 
    "<b><p align=center>This is the End</b></p>"
    OK - now to make what you're doing work, you need three logical "entities" for your application; a Model (the Application logic code), a View (the presentation layer) and a Controller which is basically the middle man, connecting the application logic with the presentation logic.

    Here goes;


    The Controller...

    PHP Code:
    <?php
    // books.php: this is the controller script

    require_once('application/init.php');

    // Include the application logic Model
    require_once('books_model.php');

    // Include the presentation layer View
    require_once('books_view.php');

    $db =& new MyDatabase(DB_DATABASEDB_SERVER);
    $db->connect(DB_USERDB_PASS);

    $booksModel = & new BooksModel($db);

    $booksView = & new BooksView($booksModel);

    echo ( 
    $booksView->toString() );
    ?>
    The Model....

    PHP Code:
    <?php
    // books_model.php

    class BooksModel {
        var 
    $db;
        var 
    $resultSet;
        function 
    BooksModel(& $db) {
            
    $this->db = & $db;
            
    $this->build();
        }
        function 
    build() {
            
    $sql ="SELECT * FROM test";
            
    $this->resultSet = & $this->db->query($sql);
        }
        function &
    getIterator() {
            return new 
    QueryIterator($this->resultSet);
        }
    }
    ?>
    The View

    PHP Code:
    <?php
    // books_view.php

    class BooksView {
        var 
    $booksModel;
        var 
    $html;
        function 
    BooksView (& $booksModel) {
            
    $this->booksModel= &$booksModel;
            
    $this->html='';
            
    $this->build();
        }
        function 
    build() {
            
    $iterator = & $this->booksModel->getIterator();
            while(
    $row $iterator->getCurrent())  {
                
    $this->html .= "<p>Book Title: <b>" $row['BookTitle'] . "</b><br><br>";
                
    $iterator->next();
                
    $this->html .= "<b><p align=center>This is the End</b></p>";
            }
        }

        function 
    toString() {
            return 
    $this->html;
        }
    }
    ?>
    If you don't like rendering the output in a class, I'd suggest using a class that loads prodecural PHP "View" scripts which contain echo statements, while using output buffering to control what actually gets sent the browser.

  5. #5
    SitePoint Enthusiast CamelToe's Avatar
    Join Date
    May 2003
    Location
    Canada
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    But I would seriously think about using some sort of Templates; else you've no way of implementing the View except for raw HTML - a problem when you begin to put your data in there ?

    Me ? I use an XML template....
    Thanks. That's what I was thinking actually. I wish I could use the XML, I have read much of your posts in the past on the subject, and I would rather use XSLT as opposed to Smarty, etc... Smarty is fun and it has a 'WOW' factor when you start using it, but once I wanted to go into production on Client sites, I had to redo alot of my code, because it just didn't have some functionality I really needed. (ie. Loops Structures need much work )

    Anyways, thanks for you post! I will look into more of the MVC actually. HarryF's comments below your post has given me more to think about when it comes to using MVC as well.

    HarryF, first of all thanks for putting together a detailed reply. I will seriously try it today or tonight.

    I will post my experience with it so other's can learn from it as well.

    I will re-consider using MVC!!

  6. #6
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Glad we could help

    I'm all for promoting MVC as basically speaking IMO it is far better programming and it increases your chances of gaining a higher payable employment;

    One reason I want to learn more about it, and I like a challenge now and again

    If you need help using XML/Sablotron just let me know and I'll see what I can do ?

  7. #7
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice example, HarryF.

    Now if you isolate your presentation logic into a view layer, you can go one more step and separate the HTML from the PHP in your view layer by having the view layer use templates. (as has been mentioned)

    There is a performance penalty, but you gain the benefit of being able to use WYSIWYG HTML editors on the HTML and text based source code editors for the php, and it allows non-programmers to make certain kinds of changes.

    When you get a large number of view classes, it also gives you more flexibility for refactoring out common presentation elements and patterns in those classes. For example you may find that the BookView class above and a hypothetical MagazineView class may differ only in the html portion, and not in the php logic portion.

    Since the view layer contains your presentation logic, you can use a simple PHPLIB style template class instead of something complicated like smarty. (If you find yourself needing logic in the template, then you can fall back and ask yourself how can I put this in the view layer.)

    So far, I've been very pleased with the results of using this MVC(PHP)+templates(HTML) approach in my own programs.

  8. #8
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice example, HarryF.

    Now if you isolate your presentation logic into a view layer, you can go one more step and separate the HTML from the PHP in your view layer by having the view layer use templates. (as has been mentioned)

    There is a performance penalty, but you gain the benefit of being able to use WYSIWYG HTML editors on the HTML and text based source code editors for the php, and it allows non-programmers to make certain kinds of changes.

    When you get a large number of view classes, it also gives you more flexibility for refactoring out common presentation elements and patterns in those classes. For example you may find that the BookView class above and a hypothetical MagazineView class may differ only in the html portion, and not in the php logic portion.

    Since the view layer contains your presentation logic, you can use a simple PHPLIB style template class instead of something complicated like smarty. (If you find yourself needing logic in the template, then you can fall back and ask yourself how can I put this in the view layer.)

    So far, I've been very pleased with the results of using this MVC(PHP)+templates(HTML) approach in my own programs.

  9. #9
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So far, I've been very pleased with the results of using this MVC(PHP)+templates(HTML) approach in my own programs.
    Can you tell us a little more about your approach?

    Thing is I've been thinking the MVC model 2 architecture (as per Sun) which seems to be en vogue in PHP right now with projects like Phrame and wondering if this is the wrong way to go for PHP applications, at least from the point of view of how the "Front Controller" is implemented. Interestingly Microsoft claimed MVC is a "bad model" at least from the point of view of ASP.NET (in the Petstore debate).

    What I'm wondering is if Sun's approach is biased by Java Servlets; i.e. they've proposed an architecture which is "servlet friendly".

    In PHP terms, people seem to be implementing MVC2 by using a central script; index.php which acts as the Front Controller.

    Now although it sounds good, keeping everything in one place, it strikes me that this is like taking over the job of web server, leads to all sorts of headaches eventually (such as you start needing to generate your own HTTP status pages from with PHP) plus the levels of abstraction you have to introduce means you can spend weeks trying to work out how an application works (eliminating one of PHP's greatest advantages - simplicity). In other words isn't the web server itself the front controller?

    PHP, like ASP.NET, benefits from having a close relationship with web server (esp. Apache), in terms of how scripts are executed as well as Apache doing the majority of the work of serving pages.

    What I wonder is if there isn't a more down to earth approach to implementing MVC in PHP which takes advantage of it's natural edge. The php.ini settings (which can also be set with .htaccess); auto_prepend_file and auto_append_file seem to me a really good place to handle "global operations" such as authentication (as well as loading classes in general), based on the requested URL etc.

    Meanwhile controllers are implemented is individual scripts on the server which visitors access directly, so with the example above the URL might be http://www.example.com/books.php

    One other thing I'm not so happy with about struts is how it makes use of http redirects for handling things like form posts. That smells bad to me; a workaround for an inadequate presentation layer. ASP.NET goes the opposite direction and implements an event model (which means you could publish your entire site using a single URL which is a bad idea if you over use it as this example demonstrates - how do you send someone a link to page 3 in the table, for example?). Of course PHP doesn't come with an event model so you have to write your own. Funnily enough there's eZHTTPPersistence. Personally I think the event model approach should only be applied to POST forms (not for GET operations) but presents a better alternative to re-directs.

    Anyway - not sure where I'm going with this. Just comparing notes I guess.

  10. #10
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I feel that there are fundamental differences between how Java integrates with the web server and how PHP integrates with the web server that make a Java style front controller less desirable when using PHP.

    I'll elaborate more on this later in the week. I have a lot to comment on in your post, HarryF.

    A couple pre-thoughts to give you an idea of where I intend to go:

    Think about what happens in the web server from the point at which the HTTP request arrives on a socket until the time that your script code gets called and how this is different for Java Scripts versus PHP scripts (or even ASP scripts).

    The .NET event model could be considered a vendor provided front controller.

  11. #11
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Interestingly Microsoft claimed MVC is a "bad model" at least from the point of view of ASP.NET
    Like, what do you expect from MS ? Their point of view if from .NET solely and no other development platform...

    Just typical of MS to make a statement like this - I have taken steps simply to ignore their work on MVC as it has absolutely nothing in relation to MVC and PHP development IMO;

    As for a 'bad model' that is rich coming from them - the very people who gave the world a 'bad framework' ie .NET ?

    No time for MS in regards to this matter; they're speaking through a hole in their a***.

  12. #12
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Do you have a reference for the "bad model" comment?

    Also, consider that in .NET and Java, the source code is transformed into an intermediate representation and it is the intermediate representation that is executed by the web server. In PHP, the programmers source code is executed directly. Because of this there are some things that .NET and Java can get away with that don't make a lot of sense in PHP.

  13. #13
    SitePoint Guru
    Join Date
    Oct 2001
    Posts
    656
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The problem with MVC on the web is that there is no clear definition of how exactly the pattern is structured. This is because the pattern was not meant for the web and it can not be applied from desktop applications to web applications 1 to 1.

    There are so many different definitions, and thus implementations, of the pattern that you can't simply speak of "MVC" in general.

    One thing that 'we' all seem to agree on is that MVC contains three components, model view and controller, but nobody is really sure how these should interact with eachother. Some people insist that XML/XSLT is the only way MVC should be implemented, others seem to insist on using templates to achieve the separation of concerns. The same thing can be said for templates, there is no absolute definition of how templates should be used, which kind of logic they may and may not contain, etc.

    .NET is not by definition MVC. In my opinion it's an even worse form of MVC, because it reverses the flow of control. Instead of some sort of Controller entity determining which View to display, the View (the .aspx page) is accessed and then the 'code behind' decides what to do. The two are so coupled that I don't think one can speak of separation of concerns there.

  14. #14
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Real quick -

    Interestingly Microsoft claimed MVC is a "bad model" at least from the point of view of ASP.NET
    That's my summary I should point out, not something MS said directly themselves.

    I'll have to hunt for the link but it came up in an analysis of the J2EE vs .NET petstores - the article was examining the use of patterns in both applications and highlighting some the shortcuts that were taken with the .NET petstore. The comment on MVC was something like "Microsoft do not believe MVC is a good choice when building web apps" - that caught my interest - the article didn't go on to explain why though. Will see if I can track it down again later.

  15. #15
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Looking over some of MVC by Microsoft they basically ripped what SUN has on their web site IMO;

    But they've went and changed portions of the text to suit their .NET framework and this in it's self confused the hell out of me...

    And as for .NET not being a MVC framework, this wouldn't suprise me in the least since IMO .NET was rushed;

    Also .NET and Java are two seperate languages and technologies and says that the two are hand in hand is unfair towards Java;

    Even though .NET is compatable with Java to some extent...

  16. #16
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Good thread!

    Quote Originally Posted by HarryF
    What I wonder is if there isn't a more down to earth approach to implementing MVC in PHP which takes advantage of it's natural edge. The php.ini settings (which can also be set with .htaccess); auto_prepend_file and auto_append_file seem to me a really good place to handle "global operations" such as authentication (as well as loading classes in general), based on the requested URL etc.
    That's exactly what I do and it works extremely well for me. I try to emulate the Model 2 (i.e. servlet) functionality as closely as possible within PHP. So in the .htaccess file in the root folder of the website I have an include_path directive set to a directory outside the web tree that contains virtually all my PHP code. There's also an auto_prepend_file directive set to the file in that afore-mentioned directory that does all the work:

    Code:
    +code/
    |  |-lib/
    |  |-prepend.php
    |  
    +www/
       |-.htaccess
       |-index.php
    .htaccess:
    Code:
    php_value include_path .:/home/accountname/code
    php_value auto_prepend_file prepend.php
    I was going to include a simplified version of prepend.php but it was taking too long to simplify it. Anyone else doing things this way?

  17. #17
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like this idea though what stops me using it is the overhead of using the auto_prepend_file settings.

    Maybe this isn't really an issue though ?

  18. #18
    SitePoint Zealot codezilla's Avatar
    Join Date
    Nov 2002
    Location
    upstairs
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is the overhead significant? I have no idea myself. However, IMHO, it doesn't really matter anyway since it allows me to program sites quickly -- and we all know speed of development is more important that speed of execution, right?

  19. #19
    SitePoint Enthusiast CamelToe's Avatar
    Join Date
    May 2003
    Location
    Canada
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Funny how one topic can open up into so many.

    HarryF, I was looking back and I found this thread
    http://www.sitepointforums.com/showt...threadid=81134

    Have you had anymore experience with utilizing an EventRegister class? Just curious.

    I haven't had a chance to move on your post (way above now) about using some MVC methods (work has kept me busy for the past 24 hrs). I am hoping to get home earlier tonight and do some experiments on it.

    Quote Originally Posted by codezilla
    ... and we all know speed of development is more important that speed of execution, right?
    You don't work in Richmond, WA USA do you?????

    Sorry bad joke. I couldn't resist

  20. #20
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Forget the remark about MVC - I can't find where I read this (though it was here but not so). The .NET petstore doesn't use MVC (as far as I can see or have read) but just models and views - the controllers are defined partly by the requested page and partly disguished in the event handlers .NET triggers. For me something like;

    Code:
    Sub Page_Load (Sender as Object, e As EventArgs)
        If IsPostBack Then
            MyForm.hide
            MyLabel.Text = 'Post received'
        End If
    End Sub
    Is not so far from;

    PHP Code:
    if ( isset[$_POST['submit'] )
         include (
    'pageWithoutForm.php');
    else
         include (
    'pageWithForm.php'); 

  21. #21
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Have you had anymore experience with utilizing an EventRegister class? Just curious.
    No - haven't done anything more than this - was gripped by an insane desire at the time. Yes it's possible using that approach but the comments to the effect of "I don't feel good about using the error handling mechanism to handle triggered events" are right - this amounts to a huge workaround.

    Perhaps we'll see some sort of event handling mechanism in PHP5 eventually. They're not far off with the error handling but it needs to be the "official solution" IMO.

    Something like;

    PHP Code:
    class MyHandler extends Page {
         function 
    page_load() {
              echo ( 
    'Page loaded' );
         }
    }

    register_event_class('MyHandler');
    register_event_handler('page_load');

    trigger_event('Page_Load'); 
    ?

  22. #22
    SitePoint Guru
    Join Date
    Nov 2002
    Posts
    841
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, here is my take on struts style front controllers and Phrame. (warning... I have not actually used struts. this is just my impression.)

    In J2EE, the java virtual machine does not get re-loaded in between requests. It remains running along side the web server. When a servlet gets initialized, it can service several requests in sequence and can keep some data in memory.

    In Struts, the ActionServlet that implements the front controller can initialize the data structures that is uses to dispatch requests once when its loaded and keep those data structures in memory across several requests.

    PHP does not have the same run time environment. Each request initializes a fresh PHP environment.

    A front controller implementation in PHP has to take this into account because it is going to incur the costs of initializing its data structures on every request. It also incurs an overhead of dispatch.

    Instead of using a struts-config.xml file, Phrame uses a mappings.php file to hold its dispatch data structures. As the application gets larger, this file will have to grow larger, taking more time to parse and load into memory on EVERY request.

    I do not care for the approach of having a central "dispatch database" like struts-config.xml or mappings.php. Its going to be hard for me to explain this very well.

    I see a parallel to how the macintosh and windows store application meta data. Windows uses a centralized database (the registry). The macintosh stores the meta data alongside the application (bundle or resource fork).

    Because the meta data and the objects that it describes are separate, there is much opportunity for mischief. If you delete the .exe file in windows, the registry is not updated to reflect the fact that the application no longer resides on your hard drive.

    On the other hand, when you delete an application file on the mac, the meta data is removed as well because it resided with the application.

    If you place an macintosh application on a floppy disk and take it to another computer, the meta data goes with it. If you do this on windows, the registry information does get copied to the file. It exists only in the central repository.

    I mistrust the requirement that every action in your web application has to have an entry in a central file. This seems to me like it would inhibit your ability to move code between web applications and make it difficult to move things around in your file stucture and in your URL structure.

    in 4.4.2.1.1 expresses a preference for using the servlet-mapping method of specifying which operation to perform. (this is what struts does) However, there is no equivelent of this technique in PHP.

    The GET parameter method can be done in PHP, but this has is own drawbacks. (even with mod_rewrite)

    In my own code, I don't use a front controller, but instead I create a small PHP file for each "action" that the application would perform. For example

    /gallery/add.php
    /gallery/approve.php
    /gallery/delete.php
    /gallery/edit.php

    These files are almost always small and they are all very similar in structure. (gallery/add.php can look alot like photo/add.php)

    Here is an example (gallery/add.php) with a controller object:

    PHP Code:
    <?php
    require $_SERVER["DOCUMENT_ROOT"] . '/config.inc';
    require_once 
    PROCATA_ROOT 'formcontroller.inc';

    class 
    AddGallery extends ValidatedFinalAction {

        function 
    perform(&$DataSource) {
            
    $Record =& new Sql();
            
    $Record->import($DataSource);
            
    $Record->insert('Galleries'
                array(
    'LinkUrl''ThumbUrl''Name''Photos''Date'));

            
    RedirectTo(BuildUrl('admin/detail.php'$DataSource, array('GalleryId')));
        }
    }

    class 
    GalleryForm extends PostFormController {
         
        function 
    InitializeValidator() { 
            require_once 
    PROCATA_ROOT 'validator.inc';
            
    $this->Validator =& new Validator();
            
    $this->Validator->addRule(new RequiredRule('LinkUrl'));
            
    $this->Validator->addRule(new RequiredRule('ThumbUrl'));
            
    $this->Validator->addRule(new RequiredRule('Name'));
            
    $this->Validator->addRule(new SizeRangeRule('LinkUrl'5128));
            
    $this->Validator->addRule(new SizeRangeRule('ThumbUrl'5128));
            
    $this->Validator->addRule(new SizeRangeRule('Name'30));
            
    $this->Validator->addRule(new SizeRangeRule('Photos'5));
        } 
         
        function 
    InitializeView() { 
             
    $this->View =& new Template('admin/galleryform.html');
        }
         
    }

    //--------------------------------------------------------------------------------
    $GalForm = new GalleryForm();
    $GalForm->DataSource =& 
        new 
    Sql('SELECT DATE_ADD(MAX(Date), INTERVAL 1 DAY) as Date from Galleries');
    $GalForm->attachAction('submit''AddGallery'); 
    $GalForm->attachDefaultAction('AddGallery'); 
    $GalForm->Run();

    ?>
    Normally, I would put the action classes into a galleryactions.inc file and the GalleryForm class into a galleryform.inc file. galleryform.inc would be shared between add.php and edit.php

    Sorry if this post is a incoherint. I didn't have time to make it make sense .

  23. #23
    SitePoint Enthusiast acostin's Avatar
    Join Date
    Mar 2002
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Elegant MVC in PHP with no overhead

    Hello,
    I have read with interests your comments on MVC and PHP, and also the issues about object persistence, and I have to agree that I have the exact same opinion about PHP and object instantiation.

    Quote Originally Posted by Selkirk
    PHP does not have the same run time environment. Each request initializes a fresh PHP environment.
    That is why OOP programming is PHP is pretty dumb, as OOP is designed to "keep the data and the procedures that process this data together", while in PHP the data is *always* loaded from a database.

    Quote Originally Posted by Selkirk
    A front controller implementation in PHP has to take this into account because it is going to incur the costs of initializing its data structures on every request. It also incurs an overhead of dispatch.

    Instead of using a struts-config.xml file, Phrame uses a mappings.php file to hold its dispatch data structures. As the application gets larger, this file will have to grow larger, taking more time to parse and load into memory on EVERY request.
    We have met the exact same problem in Krysalis. (http://www.interakt.ro/products/Krysalis). Krysalis is a complete MVC implementation in PHP, and we think that we have solved most of the problems related with the overhead brought by MVC. Let me explain more:

    "Why MVC" - because it's extremely flexible, and allows you to define with extreme ease rules of serving requests. While the default "serve from disk" method for PHP pages is pretty straight forward, it will not allow you to do enterprise level things. Like having 10 installed applications that share the same kernel, and that serves slightly different pages in logic or layout depending on the current application state. Maintanability increases exponentially.

    "How"- we have chosen to create an XML structure to define our Controller. While this might seem "overheading" at the beggining, we've optimized this to a level that it is compiled to a pure PHP file that is written much better than the average coder will write it. What we have in our sitemap.xml file are description like below:

    Code:
      <map:pipeline>
       <map:match pattern="language.xml" type="exact" internal="yes">
    	<map:cache type="xml" src="./admin/resources/descriptors/cache/desc.xml" time="360"/>
    	<map:generate src="modules/core/language/front/index.pxp" type="pxp"/>
    	<map:transform src="modules/core/language/front/{skin}.xsl"/>
    	<map:serialize type="xml" remap="no" header="no"/>
       </map:match>
      </map:pipeline>   
     
      <map:pipeline>
       <map:match pattern="search.xml" type="exact" internal="yes">
    	<map:cache type="xml" src="./admin/resources/descriptors/cache/desc.xml" time="360"/>
    	<map:generate src="modules/core/search/front/layout/index.pxp" type="pxp"/>
    	<map:transform src="modules/core/search/front/layout/{skin}.xsl"/>
    	<map:serialize type="xml" remap="no" header="no"/>
       </map:match>
      </map:pipeline>
    Which are compiled to a large switch loop that does dynamic requires of the compiled pipelines. This means that the overhead added by the controller is extremely minimal, as the file is pretty small and the code is loaded dynamically - and only the needed code:

    PHP Code:
     switch ($KTURL) {
      case (
    "language.xml"):
       
    $found true;
       require(
    "/iakt/www/htdocs/www/prod/komplete/2.5.0beta4/krysalis/webapps/komplete/cache/0.cache");
       break;
      case (
    "search.xml"):
       
    $found true;
       require(
    "/iakt/www/htdocs/www/prod/komplete/2.5.0beta4/krysalis/webapps/komplete/cache/1.cache");
       break; 
    This is the generated code for the case where the Controller rules are simple (direct association between URL and pipeline that serves an URL), but optimized code is also generated for more complex cases.


    Quote Originally Posted by Selkirk
    I mistrust the requirement that every action in your web application has to have an entry in a central file. This seems to me like it would inhibit your ability to move code between web applications and make it difficult to move things around in your file stucture and in your URL structure.

    In my own code, I don't use a front controller, but instead I create a small PHP file for each "action" that the application would perform. For example
    Should we consider then our smart compilation a "front page controller"?

    I think that a central approach has its advantages, and code reuse can be extremely well achieved if you wisely use the controller.

    Of course, alternative approaches exist, and final decision should be made regarding your familiarity with OOP, XML or with your exact project goals.

    Alexandru

  24. #24
    ********* Victim lastcraft's Avatar
    Join Date
    Apr 2003
    Location
    London
    Posts
    2,423
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi.

    Quote Originally Posted by acostin
    That is why OOP programming is PHP is pretty dumb, as OOP is designed to "keep the data and the procedures that process this data together", while in PHP the data is *always* loaded from a database.
    OO is about the development stage. It says next to nothing, as far as I know, about what happens at runtime. Can you explain the above comment?

    Quote Originally Posted by acostin
    ...compiled to a pure PHP file...
    I was wondering when code generation was going to be mentioned. Using XSLT to generate PHP code has proved a very effective combination in my experience. It allows a lot of preprocessing and PHP code can be "unrolled" (a'la loops) for efficiency. The thing is, this has no bearing on whether to use a front controller or not. You could just as easily generate the large number of script controllers as you could a single complex front controller.

    To focus the debate again, it seems to me that front controllers work better with forms and can better cope with sudden switches of context. Examples include a form taking you to different locations or a permissions failure dropping you into an error page. Scripts either force ugly redirects or, slightly better, a PHP include(). Scripts lead to more natural page navigation and can mix easily with static pages. In the rough and tumble of web development this almost always ends up the preferred option for better or worse it seems.

    Code generation can alleviate both of these with orthogonal tradeoffs such as greater developer expertise and the difficulty of refactoring XSLT code (for me at least).

    A fascinating and overdue debate. More, more,...

    yours, Marcus
    Marcus Baker
    Testing: SimpleTest, Cgreen, Fakemail
    Other: Phemto dependency injector
    Books: PHP in Action, 97 things

  25. #25
    SitePoint Enthusiast acostin's Avatar
    Join Date
    Mar 2002
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft
    Hi.
    OO is about the development stage. It says next to nothing, as far as I know, about what happens at runtime. Can you explain the above comment?
    OO is not only about the development stage. Actually, to get more close to "semantics", a class represents the description of an object, that is something with sense only at runtime. While a class is a definition of some properties and methods (a.k.a. the data and the procedures to process it under the same roof), the object represents the existence in memory of a data structure that includes the object type and the object properties.

    What I'm saying is that, for PHP, the object constructor and properties are executed/loaded each time for the persistent storage, and even if this stateless approach adds a lot to round-robin load balancing, it seems to me that objects are just hype in PHP (actually, they are very good when coding to structure your code better, and maybe to add some encapsulation, but not for many other reasons - as loose coupling can be achieved easily in other ways).

    As we know it, PHP is a language mostly used for 2 reasons - loop through recordsets to display data in a tabular form, and process HTML forms to store records in the database. I think this represents over 80% of the web development out there. As both those usages involve simple application logic and complex presentation logic, it is a pain in the *** to include the presentation logic INSIDE the obejects that are design to include the application logic. I've seen postnuke with a lot of echo "<tr><td>".$content."</td></tr>" and it was enough for me.

    Quote Originally Posted by lastcraft
    I was wondering when code generation was going to be mentioned. Using XSLT to generate PHP code has proved a very effective combination in my experience. It allows a lot of preprocessing and PHP code can be "unrolled" (a'la loops) for efficiency.
    Used wisely, loop unrolling is nice. Used without brains this can become a real pain in the *** - we've left some of our developers take this to the edge, and reached PHP unlooped code of about 800 KB for a simple form. However, after a small and effective optimization (moved the repetitive things into some old-fashioned procedures), we've ended up with less than 50 KB code for the same thing.

    Quote Originally Posted by lastcraft
    The thing is, this has no bearing on whether to use a front controller or not. You could just as easily generate the large number of script controllers as you could a single complex front controller.

    To focus the debate again, it seems to me that front controllers work better with forms and can better cope with sudden switches of context. Examples include a form taking you to different locations or a permissions failure dropping you into an error page. Scripts either force ugly redirects or, slightly better, a PHP include(). Scripts lead to more natural page navigation and can mix easily with static pages. In the rough and tumble of web development this almost always ends up the preferred option for better or worse it seems.
    Actually Krysalis is a mix between a front controller and the page controller - that are both described in the sitemap.xml file. However, we will probably use something like a Cocoon2 FlowScript in the future to simplfy the definition of simple "flow" rules in the controllers.
    [/QUOTE]

    Alexandru


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
  •