views:

78

answers:

3

Hi lad's,

I'm working on a project at the moment that requires alot of forms. I was thinking of a workaround to minimise spending hours of time on the subject. Above all else I don't want to use a framework to do this for me, I'm still learning so its important for me to understand at the core.

Ok so I have a class called form builder, which looks like this:

<?php

class formBuilder extends systemCore{

   public $token, $method=array();  

   public function __construct(){
        parent::__construct();
   }

   public function getFormMethod(&$method, $pop, $filter){//($_POST, true, filterStr)
        if($pop == true): 
        array_pop($method); 
        endif;

        foreach($method as $f => $v){
            if(is_array($v)){
                $v = implode(',', $v);
            }
            $this->method[$f] = $filter($v);
        }
        return $this->method;

   }


   public function generateToken(){
     return $this->token = mt_rand(1, 10000).md5();
   }

   public function inputField($label, $type, $id, $name, $value, $title, $css, $required){

        $required = ($required == true) ? trim('<span color="red">&lowast</span>') : '';

        // i know this seems a little redundant

        $label = (is_null($label)) ? '' : trim(htmlspecialchars($label, ENT_QUOTES));
        $type = (is_null($type)) ? 'text' : trim(htmlspecialchars($type, ENT_QUOTES));
        $id = (is_null($id)) ? '' : trim(htmlspecialchars($id, ENT_QUOTES));
        $name = (is_null($name)) ? '' : trim(htmlspecialchars($name, ENT_QUOTES));
        $value = (is_null($value)) ? '' : trim(htmlspecialchars($value, ENT_QUOTES));
        $title = (is_null($title)) ? '' : trim(htmlspecialchars($title, ENT_QUOTES));
        $css = (is_null($css)) ? '' : trim(htmlspecialchars($css, ENT_QUOTES));

        echo('
        <label for="'.$name.'">'.$label.'</label><br />
        <input type="'.$type.'" id="'.$id.'" name="'.$name.'" value="'.$value.'" title="'.$title.'" class="'.$css.'">'.$required.'<br />
        ');
   }

   //.................and so on

} // end class formBuilder

?>

What do you guys think? Should I just stick to the normal , , etc html display

$form = new formbuilder();
$form->inputField('name', 'text', 'name', 'name', 'my value', 'my title', null, true);

The CSS would be applied the same to both methods so I have not really cut any development time out here so I'm not really sure how I would play this card.

Im just looking to get some other opinions on this, cheers guys.

+2  A: 

I understand not wanting to use a framework. As a fellow PHP developer, I have avoided them for years. However, after sampling Ruby on Rails, I understood their power on such projects as yours - heavy form/data driven applications. My experience lies with PHP though, so I took a look at Cake.

With that said, you're class isn't going to give you any big wins on development time if just it simply outputs the HTML. You may have standardized form field output by encapsulating them in your FormBuilder class, but what does that get you?

The real power comes when this class can also manage form validation, saving, editing, etc. Or when it can build the form automatically from a data model (SQL schema, configuration array).

You are not going to be able to achieve all of these things. If you did, I'd argue you just build your own framework. At which point it is highly likely you spent just as much time developing the formbuilder as you would have developer the forms by hand. Unfortunately, it is highly unlikely that you will use the formbuilder again, as it would be so customized for this project.

My suggestion would be to identify the areas that give you the biggest win and develop just that into the form builder. I'd also suggest that a code generator could save you just as much time. Years ago I too wrote a custom form builder. But it simply outputted the HTML (like yours currently) that I would then copy and pasted into my PHP file. So it was static, but do you really need to dynamically build your form everytime? It allowed me to focus on the form logic and not have to waste time building the form. My guess is that's your goal.

Real frameworks, libraries, generates, etc are a balance of convention and code. I would look at CakePHP. If nothing else, read/review their Form Helper to serve as a reference for building you own. See what all it takes, then decide if that's what you need or if you just need something to generate your forms (what you have now isn't far off).

Jason McCreary
@jason: Thanks for your responce,I do plan on using a framework in the future, possibly "CodeIgnitor".The pro's I took on-board where the ones you suggest(SQL Schema, building arrays).I take your point about re-usablity but as long as I keep validating seperate, I should be fine.
Philip
You could put some basic validation into your class and still keep it reusable. Again, check out CakePHP for these types of things. Particularly I like how they pass configuration arrays and not long lists of paramaters. In addition, their simple validation rules - notempty, alphanum, email, url, etc are pretty standard. I looked at CodeIgnitor, but felt it to be more of a set of libraries than a framework. See where this takes you and then make your decision. You may find that you are naturally coding like one of these frameworks.
Jason McCreary
I like the feel of "codeIgnitor" + it can use some of the zend lib files which is a major + for me.I posteded somewhere that some of the validation can be re-used such as "email" and "password"
Philip
+2  A: 

While there's nothing wrong with re-inventing the wheel for the sake of learning, just keep in mind the fact that you're re-inventing the wheel here. :)

While many input types take very similar parameters, not all of them take the same set. There are also types that are groups of values (radios, selects), and others that treat their default values differently (textareas). Your one function to create the HTML is going to become a mess.

You might want to consider creating one class per form element type. Use an Abstract base class to provide common method names and utility methods.

Creating the form elements is only one part of the challenge. There's also labels to be concerned about, as well as layout. Will you be handling that in the class, or elsewhere?

What about data validation? Will you handle that in your form generating code? If not, how are you planning to deal with invalid form data? Will you be returning the incorrect form back to the user? It looks like you might be planning that already. Validation is a huge burden if you intend to centralize it.

Now, think of your time again. Where will your time be better spent, writing new code just for your application that may or may not get the job done, or learning how an initially intimidating but well constructed third party library works, where other people have already done all the hard work for you?

Charles
@Charles: Thanks for your responce,The inputField function I'm just using for "text/password".select, button, checkbox, will have unique functions which have already been written. I have taken into accountunique elements for each of these, such as "readonly/size/rows/cols/options" and so on.As far as validating goes, i would maybe do that in its own class, this is where @jason's point comes into effect, ie: It wouldnt be re-usable.Ok I could maybe run a preg_match for "email" and "password" and re-use those two form elements.
Philip
To display any error's I would use a popup solution with the help of this thread http://stackoverflow.com/questions/2870340/jquery-background-overlay-alert-without-onclick-event-php-responder...and simply bundle it in the systemCore class as viewer() function with different params for (ok/notok).
Philip
+2  A: 

Hi Philip

I understand the urge to not use a framework due to a lack of understanding and a want to learn. I think its a great idea to try and write classes of your own. However the best method for learning I found was to write my own simple class, like you have for form building, and then once I understood the basic concepts, take a pre-built class and try and understand it.

Like Charles said its often a good idea to re-invent the wheel for learning, once you have a sufficient grasp, it may be time to embrace the already invented wheel.

I have recently been working with Phorms, its a cool form library that stands alone, you dont need a framework so you could keep all your existing code, however someone has spent many hours creating a very good class, so why not take there hours and maybe try and improve it.

Another reason I would recommend forms to you is that the downloadable code has an error in the checkbox code and doesnt have radio button code, there are very simple fixes in the comments on the page I listed, but it would be a good challenge for yourself to try and fix the error and add a radio button class.

Hope this helps

Luke

Luke
@luke: thanks for your responce,Ill deffo look into that "Phorms" lib.I agree its only good to re-invent the wheel for learning purposes, maybe I could invent a wheel one day :)
Philip
Good to hear Philip, let us have an update on what you decide in the end, and a link to the wheel if its good :)
Luke