tags:

views:

148

answers:

3

Is this is far as you would go regarding Object Oriented PHP or can i improve it further by putting HTML into a class? How would i go about doing that? Note: The code below is using a QuickForm by PEAR. Thanks in advance.

  <?php
    //MySQL class
    require_once('database/class.mysql.php');

    //Session class
    require_once('session/class.session.php');

    //SignUp class
    require_once('access/class.signup.php');

    //QuickForm class
    require_once('HTML/QuickForm.php');

    //PHPMailer class
    require_once('thirdparty/phpmailer/class.phpmailer.php');

    //Instantiate the MySQL class
    require_once('database/dbconnect.php');
    $db = &new MySQL($host, $dbUser, $dbPass, $dbName);

    //Instantiate the Session class
    $session = new Session;

     ?>

    <html>
        <head>
            <title>Test page</title>
        </head>
        <body>
            <?php
                //Instantiate Quickform
                $form = new HTML_QuickForm('regForm', 'POST');

                ///Header
                $form->addElement('header', null, 'Quickform tutorial example!');

                //First name
                $form->addElement('text', 'fname', 'First name:', array('size' => 30));
                $form->addRule('fname', 'Please enter your first name', 'required', null, 'client');

                //Last name
                $form->addElement('text', 'lname', 'Last name', array('size' => 30));
                $form->addRule('lname', 'Please enter your last name', 'required', null, 'client');

                //Password
                $form->addElement('password', 'pass', 'Password: ', array('size' => 30));

                //Gender
                $form->addElement('radio', 'sex', 'Gender: ', 'Male', 'male');
                $form->addElement('radio', 'sex', '', 'Female', 'female');

                //County
                $form->addElement('select', 'county', 'County:', array(
                    '0' => 'Select',
                    '1' => 'Louth',
                    '2' => 'Meath'
                ));

                //Date of Birth
                $form->addElement('date', 'dob', 'Date of Birth:', array('format' => 'dMY', 'minYear' => 1950, 'maxYear' => date('Y')));

                //Submit
                $form->addElement('submit', null, 'Submit');

                //Try to validate the form
                if ($form->validate()) {
                    echo 'Hello';
                }

                //Output the form
                $form->display();
            ?>
        </body>
    </html>
+2  A: 

You may want to look into using a PHP templating system like Smarty. This will allow you to separate your HTML from the PHP code entirely. It also has added benefits of allowing you to create standard headers, footers, menus, etc. for all your pages.

The Smarty templating system in particular seems to be written with good OOP principles. You create a Smarty object, call the assign() method to inject information in a safe way, then use the display() method to generate your HTML.

Horatio Alderaan
PHP itself is a perfectly good templating language. Consider this before involving the extra overhead of a system like Smarty
Phil Brown
That's true, but it's not a terribly object oriented way of doing things. A templating engine will also have added benefits like separating concerns and caching, etc.
Horatio Alderaan
Like Mr. Brown said, using vanilla PHP for templating is very easy -- https://bitbucket.org/jsumners/pwptemplate/src . I used to use Smarty, but really all I was doing was writing "template" PHP with a different syntax. That said, if you want all of the third party plugins and such, Smarty is a fine choice.
jsumners
Thanks for your comment. I'll have a look into this.
Jonny
+1  A: 

If you want to develop web applications using object-oriented principles and other best practices, your best bet is to look into an MVC framework such as (for PHP) Symfony or CakePHP.

As well as a strong object-oriented approach with a templating framework, they are also designed with other best practices in mind such as unit testing, or object/relational mapping for database access.

jammycakes
+1  A: 

Personally, I wouldn't recommend using any sort of HTML element generating class for your page builds, especially if it also includes dynamically generated javascript.

You might be saying "Dude: what's the difference if it's all ending up as HTML anyway?"

If you do, you're left with an archaic code project by next year considering how often standards change. Sure an element like a is not likely to be depreciated any time soon, but it's base and style attributes likely will be. You've also got new special-case elements that you have to programatically account for, such as canvas. You try and validate your HTML and discover that the br and a few other tags suddenly don't accept a closing slash, let alone a closing tag. By the time you get to handling CSS in your element-generating class, you'll likely realized you just wasted all this time.

Sure programming PHP is most of the time nothing more than mixing HTML and scripting, but it's always easier for some random, inexperienced web admin to come in after you and update HTML to be current standards compliant rather than blindly digging through your PHP source. Any time there's an update anywhere in your stack or a web standard, you personally have to upgrade and update everything throughout your entire project to make sure a) your HTML-generator class still functions; b) it can handle every known HTML element and Javascript function to support every known browser. Normally, you shouldn't need to worry about updating PHP and HTML/Javascript at the same time.

So, use PHP to handle backend DB, remote fetches, user authentication, form validation, file management, and math calculations, but use caution when dedicating it to handle HTML structure.

Just IMHO. Templating is good though, since that's fundamentally what PHP website design is.

bob-the-destroyer
Thanks for your comment. It seems you have been down this road so you can look back see how you got there. I havent so im not sure what lies ahead and how to go about furthering my knowledge. Do you think it would be a good time for me to start looking into MVC frameworks or if you were in my situation how would you go about this if you wanted to separate design and code?
Jonny
@bob-the-destroyer You make an extremely good case for separating the PHP from the HTML and using a Templating system. I'm assuming you would also recommend against libraries like QuickForm that remove your control over the HTML produced?
Horatio Alderaan
@Jonny: Good question. Once you've read and re-read the PHP manual, I'd recommend the next step is just experimenting. Check out _design patterns_ to brainstorm on what schemes you'd like to try out to handle common programming problems, see what style you're comfortable with: http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29
bob-the-destroyer
@Horatio Alderaan: there's always a good reason for everything. But personally, I'd find that using a HTML-generating lib like QuickForms for _most_ of my projects would only take away from my project expected lifespan since it takes away from quickly reacting to change.
bob-the-destroyer
@Jonny: just to add on trying out design patterns such as MVC (which is actually a step up: http://en.wikipedia.org/wiki/Architectural_pattern_%28computer_science%29), you'll likely find you'll start to creep into other patterns such as Abstract factory, Factory method, Singleton, Wrapper, Bridge, Blackboard, Command, Observer, Balking patterns for bits of your PHP project or as a pattern for your entire site. At first, you may be driven insane by design and site-wide architecture patterns, but soon you'll realize that organizing your projects like this kicks ass.
bob-the-destroyer
@bob-the-destroyer Thanks. I learnt a bit about the factory and singleton for java in college. Im wondering can all those patterns be used inside the MVC pattern?
Jonny
@Jonny: you can mix and match design patters to suit your needs any way you wish for whatever current project you're working on. As I'm sure you already know, a typical use for a Singleton in PHP is for databases as it saves on multiple database reconnects and query result collisions. And, a typical use for Factory is to create objects of a type completely depending on something the user inputs. MVC from my understanding is akin to the overall project and how it's all put together to deliver content to the user.
bob-the-destroyer