PHP: Front Controller

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Buddha
    Senior Member
    • Mar 2004
    • 825

    PHP: Front Controller

    If your only building a single web page, what pattern you choose may not matter much. However, if your building entire web application then choose carefully. I've said this before, PHP only renders one page at a time. I keep saying it because understanding that is key to building efficient PHP applications.

    If you look around you'll find the most common pattern used in PHP applications is the Front Controller. It's used in CMS such Mambo and PHP-Nuke as a centralized controller. When used as a centralized controller, all request pass through one file. In the case of Mambo that file is index.php. It's also used in forums such a phpBB and Phorum as a uncentralized controller. When used as a uncentralized controller, requests maybe distributed between several specialized controllers. In the case of phpBB those would be files such as viewforum.php and viewtopic.php. Even though there are more than one controller, the individual files are acting as Front Controllers to many different pages such as individual topics.
    On a side note: Open Source software development tends to build on the work of previous projects. This of course avoids the common pit falls of reinventing the wheel. However, this method of software development doesn't seem to encourage diversity when it come to software patterns. Sometimes reinventing the wheel maybe a good thing?

    Front Controllers are not difficult to implement. A less than simple example, taken directly form PHP-Nuke:

    PHP Code:
    <?php

        
    //modules.php
     
    1    require_once("mainfile.php");
    2    $module 1;
    3    $name trim($name);
    4    
    5    
    if (isset($name)) {
    6        global $nukeuser;
    7        $nukeuser base64_decode($user);
    8        $sql "SELECT active, view FROM ".$prefix."_modules WHERE title='$name'";
    9        $result $db->sql_query($sql);
    10        $row $db->sql_fetchrow($result);
    11        $mod_active $row[active];
    12        $mod_active intval(trim($mod_active));
    13        $view $row[view];
    14        if (($mod_active == 1) OR ($mod_active == AND is_admin($admin))) {
    15            if (!isset($mop)) { $mop="modload"; }
    16            if (!isset($file)) { $file="index"; }
    17            if (ereg("\.\.",$name) || ereg("\.\.",$file) || ereg("\.\.",$mop)) {
    18                echo "You are so cool...";
    19            } else {
    20                $ThemeSel get_theme();
    21                if (file_exists("themes/$ThemeSel/modules/$name/$file.php")) {
    22                    $modpath "themes/$ThemeSel/";
    23                } else {
    24                    $modpath "";
    25                }
    26                if ($view == 0) {
    27                    $modpath .= "modules/$name/$file.php";
    28                    if (file_exists($modpath)) {
    29                        include($modpath);
    30                    } else {
    31                        die ("Sorry, such file doesn't exist...");
    32                    }
    33                }
    xx                ...
    ?>
    I guess PHP-Nuke still hasn't adopted register_globals off, so you need to know the $name variable in line 3 is from the URL query string. Lines 8 - 13 fetch some information about the module identified by $name. Line 14 determines if the module is active or not, admin see even inactive modules as you can see. Skipping down to lines 26 through 33, you can see how it loads this particular module identified by $name if view equals zero. But that's just the beginning the page is no where near rendered yet.

    PHP-Nuke may not be a simple example of a front controller but it sure shows how Front Controllers are being misused. We're no where near rendering a page and have already included up to 5 files, connected to the database, executed at 2 database query and have included 34kb of functions the final page may or may not need. Is this really worth trying to replace the http server? After all isn't it the job of the server to server files?

    With PHP the overhead associated with the Front Controller isn't a one time thing, it occurs on every page. That can add up as traffic increases. Nothing wrong with using Front Controllers as long as you understand the cost associated with using them with PHP. Remember this ain't Java, yet?

    Well enough for now, next time maybe we'll take a look at Intercepting Filters and how they can help us.
    "Whatcha mean I shouldn't be rude to my clients?! If you want polite then there will be a substantial fee increase." - Buddha
  • -Oz-
    Senior Member
    • Mar 2004
    • 545

    #2
    So are you saying that using front controllers is a bad idea?

    My CMS does not use them currently, but if its a good idea I may switch.
    Dan Blomberg

    Comment

    • Buddha
      Senior Member
      • Mar 2004
      • 825

      #3
      Originally posted by -Oz-
      So are you saying that using front controllers is a bad idea?
      No. Definitely not. Front Controllers are tools. Like all tools they need to be applied properly.

      Originally posted by -Oz-
      My CMS does not use them currently, but if its a good idea I may switch.
      Interesting. Could you elaborate? Been looking for some examples that don't use Front Controllers.

      Currently, I'm re-writing a lot of code to fit my new framework which uses Intercepting Filters for session and logging. Supporting scripts like authentication and form2mail are just standard scripts with simple filenames. They can be dropped in where needed.
      "Whatcha mean I shouldn't be rude to my clients?! If you want polite then there will be a substantial fee increase." - Buddha

      Comment

      • -Oz-
        Senior Member
        • Mar 2004
        • 545

        #4
        Each module of my CMS (such as news) is seperate.

        http://www.gamersmark.com/news/ the scripts is news.php and it controls all of the news stuff. /reviews/view/ the script is view.php and it only controls reviews.

        It means that it only accesses what is needed (such as reviews or previews). I have one config file that loads the function to connect to the database and other neccesary functions. Nothing is actually executed until it is called in each module.
        Dan Blomberg

        Comment

        • Jonathan
          Senior Member
          • Mar 2004
          • 1229

          #5
          I use a centralized header.php with
          all my mySQL info, as well as the CSS, tables (for menu),
          tables for image slices, etc. -- all combined (basicly up to the <BODY> tag).

          Then I also have centralized footer.php
          with little copyright and closing body and html tags
          "How can someone be so distracted yet so focused?"
          - C

          Comment

          • -Oz-
            Senior Member
            • Mar 2004
            • 545

            #6
            As do I, but nothing is run from there, its static that way it cuts down on CPU usage.
            Dan Blomberg

            Comment

            • Jonathan
              Senior Member
              • Mar 2004
              • 1229

              #7
              Hmm; not sure if mine is static...

              In the header.php file it uses PHP @ very top to
              set the mySQL info (host, pass, user, etc.) as well
              as the site's title, absolute URL, etc.

              So if I need to move, say the images folder
              I just edit one line so it fixes all the table
              coding for the image slices I use
              "How can someone be so distracted yet so focused?"
              - C

              Comment

              • Buddha
                Senior Member
                • Mar 2004
                • 825

                #8
                Here's what my setup looks like:

                PHP Code:
                // initializer sets up the common variables ($_CFG)
                // sets up some common functions for logging (other as needed)
                // gets the session ($_CFG['session'])
                // gets the user ($_CFG['user'])
                // if no user data is available no other files are included
                include initializer.php// this is prepended by PHP

                // my administrative level compiles pages
                // although the all content is store in a database
                // the static content can be embedded as variables

                // set some variables to fill the view
                // these varibles can be stored any where
                // these here are compiled into page to aviod
                // hitting the data base for them
                $_VIEW['header_title'] = 'TEST PAGE';
                $_VIEW['header_robots'] = 'NOINDEX, NOFOLLOW';
                $_VIEW['header_description'] = 'TEST PAGE FOR DSF';
                $_VIEW['header_keywords'] = 'just a test';
                $_VIEW['content_area'] = 'Big long Buddha like rant here...';

                // related article model here
                ...
                // comment model here
                ...

                // this is a compiled template
                // different pages may have different views
                // with different components compiled
                // such as 'comments' or 'related articles'
                include $_CFG['path_templates'].'view.php';

                include 
                finalizer.php// this is appended by PHP 
                "Whatcha mean I shouldn't be rude to my clients?! If you want polite then there will be a substantial fee increase." - Buddha

                Comment

                • Pedja
                  Senior Member
                  • Mar 2004
                  • 329

                  #9
                  I am developing CMS on my own, because none satisfied me. I am building this forstly to create tool for myself, to allow me produce sites faster.

                  I se nothing bad in front controler script as long as it is not misused. I would like to hear about solutions that do not follow front controller idea and they are easy to customize, build new modules and maintain.

                  Of course I do use front controler, it handles everything, but nothing more, what is needed in each script usd on site: session nagement, user authentification, privileges check, master template loading etc. It is quite short code.

                  Modules I devolop in this CMS are mostly independent about doint their jobs. All mofule has to do is include front controler script at it's begining to make it use all stuff from site thatit needs. Everything else is programmed within module. Modules may be run directly, and in fact, most of the things are run that way (www.domain.com/news, www.domain.com/forum, www/domain.com/docs etc...). It works that modules ar running front controller, but also it si possible to roun any module by running front controller directly and specifying module parameters. What will be used depends on specific module need.

                  Gains? Easy maintenance, eachmodule contains everything needed, when you are customizing it you customize module code or temeplate. code is cleaner tightier, and some of the module behaviour which is controlled by front contoleer is set by parameters.

                  As one said, it is all just about proper use.

                  Comment

                  • Buddha
                    Senior Member
                    • Mar 2004
                    • 825

                    #10
                    I am developing CMS on my own, because none satisfied me. I am building this forstly to create tool for myself, to allow me produce sites faster.
                    I'm on my third attempt to perfect my own CMS. The CMS I'm working on now, doesn't have a front controller as you can see from that previous post. I'm seeing a number of benefits from losing the front controller such as:
                    • Every file becomes it's own cache.
                    • Descriptive search engine friendly filename without a lot of mod_rewrite work.
                    • Log files with meaningful statistics.
                    • There's also a slight speed increase.


                    My administrative pages do use Page Controllers and I'm using PHP templates. So the code is pretty clean and organized. Now if I can just get it all documented.
                    "Whatcha mean I shouldn't be rude to my clients?! If you want polite then there will be a substantial fee increase." - Buddha

                    Comment

                    Working...