SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 49 of 49
  1. #26
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    I don't understand this... Can someone explain to me how these form makers are different from writing out a form? Both seem to require manually entering all arguments and types of input necessary. One is just written in a different form than the other.
    The biggest annoyance for form writing for me is validating it. For tiny forms like a simple contact form, i generally do only server side validation, but for a large form i will usually build a javascript one and a php one. Thus having some sort of an automated process to validate and then return error results automatically save quite a bit of time.

    And like Hammer65 said, the hardest part to automation that i've found is having an easy way to style it according to the individual needs.

  2. #27
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Where place i was working on keeping it for purpose of styling for different needs It is real easy to extend the class and only adjust the __toString functions to your taste and that is all you would have to do.

    Once I get my computer set backup I'm going to go at it again. Wasn't doing this just cause but it gave me something to learn more about OOP and advance in that area.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  3. #28
    SitePoint Zealot
    Join Date
    Sep 2007
    Posts
    136
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wanted to get rid of all the unneccessary coding I had to do and wrote all the scripts you're talking about a couple years ago. I've just been modifying them slightly since. I use them so often, when I start a project and I don't have these classes included, I pretty much forget how I did the original code!

    Here's an html class I wrote, great for some form stuff, and my image display functions are golden! I couldn't live without them. Some of the stuff is a little cryptic, and some of the functions are because this version of the class is tailored to a specific project, but you can do as you like.

    html.class.php
    Code PHP:
    <?
     
     
    class html {
     
        function select_list_simple($name, $options, $selected = null, $extra = false) {
            echo "<select name=\"".htmlspecialchars($name)."\"".(($extra!==false)? " ".$extra : "" ).">";
     
            foreach ($options as $key => $value) {
                echo "<option value=\"".htmlspecialchars($key)."\"";
     
                if($selected==$key)
                    echo " selected";
                if(is_array($value))
                    echo " ".$value['extra'].">".htmlspecialchars($value['value'])."</option>";
                else
                    echo ">".htmlspecialchars($value)."</option>";
            }
     
            echo "</select>";
        }
     
        /****************/
     
        function input_box($name, $value = "", $extra = false, $size = "15") {
            if($value!="")
                $value = htmlspecialchars($value);
     
            echo "<input type=\"text\" name=\"".htmlspecialchars($name)."\" value=\"".$value."\" size=\"$size\"";
     
            if($extra!==false)
                echo " ".$extra;
     
            echo " />";
     
        }
     
        /****************/
     
        function textarea($name, $value = "", $extra = false, $rows="8", $cols="40") {
            if($value!="")
                $value = htmlspecialchars($value);
     
            echo "<textarea name=\"".htmlspecialchars($name)."\" rows=\"$rows\" cols=\"$cols\"";
     
            if($extra!==false)
                echo " ".$extra;
     
            echo ">$value</textarea>";
     
        }
     
        /****************/
     
        function closeButton($action = false) {
            $a = "onmouseover=\"this.className='closeButton2'\" onmouseout=\"this.className='closeButton1'\" onmousedown=\"this.className='closeButton3'\" onmouseup=\"this.className='closeButton2'\"";
     
            $t = "<a href=\"#\"".(($action!==false)? " onclick=\"$action\"" : "")." title=\"Close\" class=\"closeButton1\" $a>&nbsp;</a>";
     
            return $t;
        }
     
        /****************/
     
        function printButton($action = false) {
            $a = "onmouseover=\"this.className='printButton2'\" onmouseout=\"this.className='printButton1'\" onmousedown=\"this.className='printButton3'\" onmouseup=\"this.className='printButton2'\"";
     
            $t = "<a href=\"#\"".(($action!==false)? " onclick=\"$action\"" : "")." title=\"Close\" class=\"printButton1\" $a>&nbsp;</a>";
     
            return $t;
        }
     
        /****************/
     
        function input_box_small($name, $value = "", $extra = false, $size = "15") {
     
            $extra = "class=\"smallinput\" ".$extra;
     
            self::input_box($name, $value, $extra, $size);
        }
     
        /****************/
     
        function form_hidden($name="", $value="") {
            return "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
        }
     
        /****************/
     
        function checkbox($name, $value, $checked = false, $extra = "") {
            if($value!="")
                $value = htmlspecialchars($value);        
     
            echo "<input type=\"checkbox\" name=\"".htmlspecialchars($name)."\" value=\"".$value."\"";
     
            if($checked==true)
                echo " checked";
     
            if($extra!==false)
                echo " ".$extra;
     
            echo " />";
        }
     
        /****************/
     
        function toolbar(&$buttons) {
        //  array() $buttons =>
        //    string 'title'   >> label
        //    string 'action'  >> click action
        //    bool 'disabled'  >> disabled
     
            echo "<div class=\"toolbar\">\n";
     
            foreach($buttons as $button) {
                echo "<input type=\"button\" class=\"base\" name=\"".$button['title']."\"";
                if($button['disabled'])
                    echo " disabled";
                else if($button['action'])
                    echo " onclick=\"".$button['action']."\"";
     
                echo ">";
            }
     
            echo "</div>";
     
        }
     
        /****************/
     
        function find_image($img) {
            $try1 = _TEMPLATE_DIR."/images/".$img;
            $try2 = "images/".$img;
            if(file_exists($try1))
                return $try1;
            else if(file_exists($try2))
                return $try2;
            else
                return false;
        }
     
        /****************/
     
        function img_f($img, $alt = "", $extra = "") {
            return self::img(self::find_image($img), $alt, $extra);
        }
     
        /****************/
     
        function img($img, $alt = "", $extra = "") {
            if(!file_exists($img))
                return false;
     
            list($width, $height, $type, $attr) = getimagesize($img);
            $alt = htmlspecialchars($alt, ENT_NOQUOTES);
     
            return "<img src=\"$img\" width=\"$width\" height=\"$height\" alt=\"$alt\" border=\"0\" $extra />";
        }
     
        /****************/
     
        function tI($num = 0) {
     
            return "tabindex=\"".$num."\"";
     
        }
     
        /****************/
     
        function tag_javascript($url = false) {
     
            if(!$url)
                return false;
            else
                return "<script src=\"$url\" type=\"text/javascript\"></script>";
        }
     
        /****************/
     
        function tag_stylesheet($url = false) {
     
            if(!$url)
                return false;
            else
                return "<link href=\"$url\" rel=\"stylesheet\" type=\"text/css\" />";
        }
     
        /****************/
     
        function make_topBar(&$links, $active = false) {
            if(count($links)<1)
                return false;
     
            echo "<ul id=\"topmenu\">\n";
     
            $count = 1;
            foreach($links as $key => $val) {
                echo "<li onclick=\"$val\" ".(($active==$count)? "class=\"on\"" : "")."><span><span><span>";
                echo $key;
                echo "</span></span></span></li>";
                $count++;
            }
     
            echo "</ul>";
     
    ?>
     
    <script type="text/javascript">
    var TopBar = Class.create();
    TopBar.prototype = {
        initialize: function() {
            this.barObj = $('topmenu');
     
            var itemrows = this.barObj.getElementsByTagName('li');
            this.buttons = $A(itemrows);
            this.activeButton = null;
     
            parentObject = this;
            if(this.buttons.length>1) {
                this.buttons.each(function(node){
                    if(node.className=='on') {
                        parentObject.activeButton = node;
                        node.onmouseout = function() {
                            this.className='on';
                        }
                        node.onmouseover = function() {
                            this.className='on';
                        }
                    }
                    else {
                        node.onmouseout = function() {
                            this.className=null;
                        }
                        node.onmouseover = function() {
                            this.className='over';
                        }
                    }
     
                    Event.observe(node, 'click', function() {
                        if(parentObject.activeButton == node)
                            return;
                        node.className='on';
                        node.onmouseout = function() {
                            this.className='on';
                        }
                        node.onmouseover = function() {
                            this.className='on';
                        }
     
                        if(parentObject.activeButton == null)
                            return;
     
                        parentObject.activeButton.className = null;
                        parentObject.activeButton.onmouseout = function() {
                            this.className=null;
                        }
                        parentObject.activeButton.onmouseover = function() {
                            this.className='over';
                        }
     
                        parentObject.activeButton = node;
                    });
     
                });
            }
            else {
                this.buttons.each(function(node){
                      node.onmouseout = function() {
                          this.className=null;
                      }
     
                      node.onmouseover = function() {
                          this.className='over';
                      }
     
                });
            }
     
        }
     
    };
    var topMenu = new TopBar();
    </script>
     
    <?
     
        }
     
        /****************/
     
        function error_message($message) {
            echo "<div class=\"error\">".$message."</div>";
        }
     
        /****************/
     
        function comment($message) {
            echo "<!-- ".$message." -->";
        }
     
        /****************/
     
    }
     
     
    ?>

    I like the image functions the most, cause this project is based on some visual templates, with default styles as well. So to display an image all I do is html::img_f("someimage.gif")

    Then it will automatically look for the template version of that image, if there is none, it gets the default one instead, then finds the size of the image, and outputs my full xhtml1.1 compliant <img> tag!

  4. #29
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That, similar to my first example of form generating, isn't actually OOP - it's a set of functions held within a class, without the use of actual objects.

    Anyway, I'm doing some work on a mysql class, which I've called MysqlBoost. It's only just started, here it is, but I'm coming up with an error:
    Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\wamp\www\classes\mysql.class.php on line 63
    This is because it can't find the connection previously passed to MysqlBoost. Here's the class:
    PHP Code:
    <?
    class MysqlBoost{
        var 
    $host$user$pass$dbname$connection$database;
        function 
    __construct($host$user$pass$database){
            
    $this->host $host;
            
    $this->user $user;
            
    $this->pass $pass;
            
    $this->dbname $database;
        }
        
        function 
    connect(){
            
    $this->connection mysql_connect($this->host$this->user$this->pass);
            
    $this->database mysql_select_db($this->dbname$this->connection);
        }
        
        function 
    __sleep(){
            return array(
    "Host" => $this->host"Username" => $this->user"Password" => $this->pass"Database"$this->dbname);
        }
        
        function 
    __wakeup(){
            
    $this->connect();
        }
        
        function 
    query($statement){
            return new 
    MysqlBoost_Query($statement, );
        }
        
        function 
    select($fields$tables$wherefield null$wherevalue null$order null$limit=null){
            
    $fieldstring "";
            
    $fieldformat "`%s`";
            
    $sqlformat "SELECT %s FROM %s%s%s%s";
            if(
    is_array($fields)){
                
    $fieldstring sprintf($fieldformatimplode("`,`"$fields));
            }else if(
    $fields != "*"){
                
    $fieldstring sprintf($fieldformat$fields);
            }else{
                
    $fieldstring $fields;
            }
            if(
    is_array($tables)){
                
    $tablestring sprintf($fieldformatimplode("`,`"$tables));
            }else{
                
    $tablestring sprintf($fieldformat$tables);
            }
            if(isset(
    $wherefield$wherevalue)){
                
    $wherestring sprintf(" WHERE `%s` = '%s'"$wherefield$wherevalue);
            }
            if(isset(
    $order)){
                
    $orderstring sprintf(" ORDER BY %s"$order);
            }
            if(isset(
    $limit)){
                
    $limitstring sprintf(" LIMIT %s"$limit);
            }
            
    $statement sprintf($sqlformat$fieldstring$tablestring$wherestring$orderstring$limitstring);
            return new 
    MysqlBoost_Query($statement);
        }
    }

    class 
    MysqlBoost_Query{
        var 
    $queryString;
        var 
    $query;
        function 
    __construct($query){
            
    $this->queryString $query;
            
    $this->query mysql_query($query);
        }
        function 
    returnQuery(){
            return 
    $this->query;
        }
    }
    ?>
    To implement it, you do this:
    PHP Code:
    <?
    $MysqlBoost 
    = new MysqlBoost("mysql.host.com""username""password""dbname");
    $MysqlBoost->select(array("field1""field2"), "table""field2""somevalue""field1 ASC""0, 5")->returnQuery();
    ?>
    Without setting MysqlBoost_Query->query to the mysql_query, it would echo the SQL query sent to MysqlBoost_Query

    I was trying to give each query it's own class - similar to Logic_Earth's technique. It looks better like this, and feels more structured.

    If you run this, you will notice that when calling the MysqlBoost_Query class (from within the MysqlBoost class), it doesn't find the mysql connection. This is because the database connection is within the MysqlBoost class.


    So, I thought of adding the connection variable to the MysqlBoost_Query instiation, however that would be very inefficient because it would need to keep connecting to the database every time a query is fired.

    I also tried calling MysqlBoost_Query as an extention of MysqlBoost, in the hope that it would carry the connection variable through, but it didn't work.

    The only other option I can think of is that a user defines the connection before the class is instantiated, however that kind of loses the whole point about it being OOP.


    So, what do you guys recommend I do?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  5. #30
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    I don't see $this->connect() being called anywhere in that code. I believe that is the problem.

    PHP Code:
    $MysqlBoost = new MysqlBoost("mysql.host.com""username""password""dbname");
    $MysqlBoost->connect();
    $MysqlBoost->select(array("field1""field2"), "table""field2""somevalue""field1 ASC""0, 5")->returnQuery(); 
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  6. #31
    SitePoint Zealot
    Join Date
    Sep 2007
    Posts
    136
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    So, what do you guys recommend I do?
    extend http://www.php.net/manual/en/ref.mysqli.php

  7. #32
    SitePoint Evangelist catweasel's Avatar
    Join Date
    Apr 2007
    Location
    Goldfields, VIC, Australia
    Posts
    518
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    I don't understand this... Can someone explain to me how these form makers are different from writing out a form? Both seem to require manually entering all arguments and types of input necessary. One is just written in a different form than the other.
    In the case of my form class this code -
    PHP Code:
    $columns $db->showColumns('clients');
    $formObj = new AutoForm($columns);
    printf("<form method='post' action='somescript.php'> 
            %s 
            <div class='formElem'> 
            <input type='submit' value='Update Records'> 
            </div> 
            </form>"
    ,$formObj->buildForm()); 
    replaces all of this -
    HTML Code:
    <form method='post' action='somescript.php'>
    <div class='formElem'>
    Client<br>
    <input type='text' name='client' value=''>
    </div>
    <div class='formElem'>
    Contact Name<br>
    <input type='text' name='contact_name' value=''>
    </div>
    <div class='formElem'>
    Address<br>
    <input type='text' name='address' value=''>
    </div>
    <div class='formElem'>
    City<br>
    <input type='text' name='city' value=''>
    </div>
    <div class='formElem'>
    State<br>
    <select name=state><option value='ACT' selected>ACT</option>
    <option value='NSW'>NSW</option>
    <option value='NT'>NT</option>
    <option value='QLD'>QLD</option>
    <option value='SA'>SA</option>
    <option value='TAS'>TAS</option>
    <option value='WA'>WA</option>
    <option value='VIC'>VIC</option>
    </select>
    </div>
    <div class='formElem'>
    Postcode<br>
    <input type='text' name='postcode' value='' size='4' maxlength='4'> 
    </div>
    <div class='formElem'>
    Phone<br>
    <input type='text' name='phone' value=''>
    </div>
    <div class='formElem'>
    Alternative Phone<br>
    <input type='text' name='alternative_phone' value=''>
    </div>
    <div class='formElem'>
    Fax<br>
    <input type='text' name='fax' value=''>
    </div>
    <div class='formElem'>
    Email<br>
    <input type='text' name='email' value=''>
    </div>
    <div class='formElem'>
    Url<br>
    <input type='text' name='url' value=''>
    </div>
    <div class='formElem'>
    Status<br>
    <select name=status><option value='active' selected>active</option>
    <option value='suspended'>suspended</option>
    </select>
    </div>
    <div class='formElem'>
    <input type='submit' value='Update Records'>
    </div>
    </form>
    If I wanted the form to be auto filled out with values from a database record I would do this -
    PHP Code:
    $columns $db->showColumns('clients');
    $result $db->execute("select * from clients where i=?",3); // fetch client number 3
    $row $result[0];
    $formObj = new AutoForm($columns,$row);
    printf("<form method='post' action='somescript.php'> 
            %s 
            <div class='formElem'> 
            <input type='submit' value='Update Records'> 
            </div> 
            </form>"
    ,$formObj->buildForm()); 
    Hammer65 is right, the hardest bit is keeping flexibility. Which is why I have a buildSpecial function in the class and also a function to return an array of all the form elements so I can add or tinker with it further before printing it out.

    I have a completely seperate set of classes for validation and another lot for database connections. I prefer to keep tasks seperate from each other.

  8. #33
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why not just write a function for it then, instead of an entire class? If I got a frequently returning form, I just write a function that places it and takes arguments that're standard on NULL. When the form doesn't pass server-side validation, the function is called again, with the values the user entered passed on as parameters. Saves far more trouble than using a class.

    Code like this:
    PHP Code:
    echo '<form name="my_form" action="index.php" method="post">
    <div class="label">Field 1</div><div class="input"><input type="text" name="my_input" id="my_input" /></div>
    <div class="label">Field 2</div><div class="input"><input type="text" name="my_input_2" id="my_input_2" /></div>
    <div class="submit"><input type="submit" name="my_submit" id="my_submit" value="Submit" /></div>
    </form>'

    will get replaced with this:
    PHP Code:
    my_form(); 
    Beat that with a pointy stick using a class setup :P

    Also, I never understood how client-side form validation (the Javascript stuff) keeps people from turning off Javascript in their browsers and sending input on that shouldn't have been sent. Can anybody explain how that works?

  9. #34
    Keep it simple, stupid! bokehman's Avatar
    Join Date
    Jul 2005
    Posts
    1,935
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    Why not just write a function for it then, instead of an entire class?
    Having a class used by all pages would be better. For a start errors would be tracked down sooner. Of course you could still have your function that outputs a form, but it would use the form class to produce the output, not just echo (non-standard) HTML to the page like yours does.
    Quote Originally Posted by Kon-Tiki View Post
    Also, I never understood how client-side form validation (the Javascript stuff) keeps people from turning off Javascript in their browsers and sending input on that shouldn't have been sent. Can anybody explain how that works?
    Everything still needs to be re-validated serverside for just that reason and because the request may not be coming from your form. Clientside validation is used to reduce server load and allow faster interaction with the user, nothing more.

  10. #35
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    Why not just write a function for it then, instead of an entire class? If I got a frequently returning form, I just write a function that places it and takes arguments that're standard on NULL. When the form doesn't pass server-side validation, the function is called again, with the values the user entered passed on as parameters. Saves far more trouble than using a class.
    Thats ugly and very in flexible. If you want to change it half way though you have to reconstruct it change the portion you need to then put it back together.

    While the class I just alter one thing. For instance
    PHP Code:
    form = new FormMaker('http://sandbox.loc/');

        
    $user $form->addInput('text''username');
        
    $user->addLabel(null'wrap');

        
    $form->insertBreak();

        
    $pass $form->addInput('password''password');
        
    $pass->addLabel(); # creates a label with the text Password:

        
    $form->insertBreak("<br>\n"); # Custom breaks;

        
    $text $form->addTextarea('testtext''some sample data');
        
    $text->addLabel('Some Text Area''wrap');

    print 
    $form
    Now say I wanted to change the way the label element on the textarea. I want it behind instead of infront.
    $text->label->setPosition('behind');

    Or i wanted to change the name of the username field.
    $user->setName('Newname');

    I can do that at run time as well. and if i did it after creating the label, it will update it too.
    Completely editable until printed.

    There are less issues and the code looks much cleaner and easier to read for non-programmers.
    Lets not get into the maintainable aspect right now.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  11. #36
    SitePoint Evangelist catweasel's Avatar
    Join Date
    Apr 2007
    Location
    Goldfields, VIC, Australia
    Posts
    518
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    Why not just write a function for it then, instead of an entire class? If I got a frequently returning form, I just write a function that places it and takes arguments that're standard on NULL
    Could you post this function so we can all take a look? It must one very, very long function.

    Also, I never understood how client-side form validation
    Like Bokehman says.. this is a usability thing. It's far more polite to intercept obvious errors on the client side so the user doesn't have to go through the process of submitting the form before discovering problems. Client side validation is not done for security, its done for usability. It's always backed up with server side validation.

  12. #37
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Catweasel: I already posted it, and it's far less long than that class of you guys.
    Logic_Earth: That sounds like just as much work as just writing the form out each time.
    Bokehman: Aye, that explains the client-side validation then. Thanks for clearing that up

  13. #38
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Depends how you look at it. There is a lot of automation going on thats not visible in that example.

    But until its actually printed on screen I can change every which way I like.
    I can pull it into different parts of the site then change it to fit with out writing one bit of html.

    I can set it up to allow the user to edit for like custom form widgets either a public thing or admin portion of the site.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  14. #39
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks Logic_Earth (Slaps head) - I can't beleive I didn't call connect(). I was too busy looking for advanced connection passing between sub-classes, forgetting that a mysql connection is global (Slaps head again). lol. Could you suggest any improvements to the current code? I was thinking of declaring the sql statement formats in constants.

    @Kon-Tiki:The whole point about classes is that you can add bits in by adding just one line. You may not want to include these extras in other forms, so you'd be using two different functions to create forms. That's the amazing power of OOP
    Beat that with a pointy stick using a non-class setup :P
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  15. #40
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Logic, when do you use
    PHP Code:
    $this-> 
    and
    PHP Code:
    self:: 
    and what are the differences?
    Thanks,
    Jake Arkinstall
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  16. #41
    SitePoint Evangelist catweasel's Avatar
    Join Date
    Apr 2007
    Location
    Goldfields, VIC, Australia
    Posts
    518
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    Catweasel: I already posted it, and it's far less long than that class of you guys.
    No you haven't posted any function.. a function begins with the word 'function'

    I'd like to see something like this -
    PHP Code:
    function myFormMakingFunction($table) {
        
    // some code in here that would dynamically build a form 
        // after being given a database tablename.


  17. #42
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Logic_earth: You might not be writing one single line of HTML, but you'd be writing just as many lines of PHP as you would otherwise do in HTML.

    Arkinstall: Aye, that's the only flaw with the functions way to work: Adding one element requires either rewriting the entire function, or cutting it up into several ones, then manually writing the extra HTML inbetween function calls. To me, that still seems like a better way to go if you have several parts of forms that return, but not entire forms, instead of writing all the HTML code you'd otherwise write, time and time over again, but in class operations instead of in plain HTML. Only problem with this would be validation. That will require separate functions as well.

  18. #43
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Catweasel: Here's one I wrote the other day:
    PHP Code:
    function contact_form($name NULL$mail NULL$tel NULL$subject NULL$msg NULL) {
        if (empty(
    $_POST["sbmt_cntct"])) {
            echo 
    '<form name="frm_contact" action="' $_SESSION["lang"] . '/contact" method="POST">
            <div class="contact_left">
                <b>' 
    LANG_NAME ':</b><br /><input type="text" name="cntct_name" value="' $name '" /><br />
                <b>Email:</b><br /><input type="text" name="cntct_mail" value="' 
    $mail '" /><br />
                <b>Tel:</b><br />
                <input type="text" name="cntct_tel" value="' 
    $tel '" size="8" maxlength="13" />
                <select name="slct_cntry">
                    <option value="Nederland">NL</option>
                    <option value="Belgie">BE</option>
                    <option value="Frankrijk">FR</option>
                    <option value="Luxemburg">LX</option>
                </select>
                <br /><br />
                <input type="submit" name="sbmt_cntct" value="' 
    LANG_SEND '" />
            </div>
            <div class="contact_right">
                <b>' 
    LANG_SUBJECT ':</b><br /><input type="text" name="cntct_subject" value="' $subject '" /><br />
                <b>' 
    LANG_MSG ':</b><br />
                <textarea name="cntct_msg" rows="10" cols="54" value="' 
    $msg '"></textarea></div>
            <div class="clearer"></div>
            </form>'
    ;
        }
        else {
            
    $name $_POST["cntct_name"];
            
    $address $_POST["cntct_mail"];
            
    $subject $_POST["cntct_subject"];
            
    $msg $_POST["cntct_msg"];
            
    $country $_POST["slct_cntry"];        

            
    $name strip_tags($name);
            
    $name stripslashes($name);
            
    $name htmlspecialchars($name);
            
            
    $subject strip_tags($subject);
            
    $subject stripslashes($subject);
            
    $subject htmlspecialchars($subject);
        
            
    $msg strip_tags($msg);
            
    $msg stripslashes($msg);
            
    $msg htmlspecialchars($msg);
            
            
    $tel_text $_POST["cntct_tel"];
            
    $tel_text strip_tags($tel_text);
            
    $tel_text stripslashes($tel_text);
            
    $tel_text htmlspecialchars($tel_text);
            
            
    $tel_text $tel_text " (" $country ")";
        
            
    $ok TRUE;

            echo 
    "<div class='clearer'></div>";
            if (empty(
    $name)) {
                echo 
    "<div class='error'>" LANG_NO_NAME "</div>";
                
    $ok FALSE;
            }
            if (!
    eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$"$address)) {
                echo 
    "<div class='error'>" LANG_NO_ADDRESS "</div>";
                
    $ok FALSE;
            }
            if (empty(
    $subject)) {
                echo 
    "<div class='error'>" LANG_NO_SUBJECT "</div>";
                
    $ok FALSE;
            }
            if (empty(
    $msg)) {
                echo 
    "<div class='error'>" LANG_NO_MSG "</div>";
                
    $ok FALSE;
            }
            
            if (
    $ok == FALSE) {
                unset(
    $_POST["sbmt_cntct"]);
                
    contact_form($name$address$tel_text$subject$msg);
            }
            else {
                
    $mail $name " heeft een bericht met onderwerp " $subject " achtergelaten op <my_site>:\n\n"
                
    $subject "\n\n" $msg "\n\n" "Antwoorden naar: " $address " of op\n" $tel_text;
                
                
    $mail_sent mail("<my_address>""Bericht van <my site>"$mail"FROM: <my_site_email>");
                if (
    $mail_sent == TRUE) echo LANG_MSG_SENT "<br />";
                else echo 
    LANG_MSG_NOT_SENT "<br />";
            }
        }

    (I took out some information like email address and such. Won't work until you fill a good one in there)

  19. #44
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    $this is available when a method is called from within an object context. $this is a reference to the calling object.
    So basically you always use $this.

    self:: is part of scope resolution and static. basically self:: is the same thing as doing ClassName:: but much shorter.

    There is a second one parent:: this will call the parent method of the extending class. However the method called doesn't have to be static nor does it act like a static function.

    PHP Code:
    class Form_Element_Input extends Form_Element {

        public function 
    __construct ($type null$name null$value null$attr null) {

            
    $this->elm[1] = 'type';

            
    parent::__construct($name$value$attr);
            
    $this->setType($type);

        } 
    In the parent class I already written the code to handle $name, $value, and $attrbitues. So there is no need to redefine those. If the child has overridden the parent functions the parents::__construct() will call those. Very handy.

    ref.
    http://www.php.net/manual/en/languag...ekudotayim.php
    http://www.php.net/manual/en/language.oop5.static.php
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  20. #45
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    @Kon-Tiki: That's the problem. A function is specific to it's job.

    A class would be to create a form and it's handling. Therefore, you'd just need to set the fields, and tell it what to do with the data, and you've got yourself a contact form. With the same class, you can create a registration script, login script, product uploader, any kind of form you need.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  21. #46
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm, in some cases, it can be useful, I guess, but only if the overhead's kept to a bare minimum and you're not required to write more than one or two lines for forms that would otherwise be 50 lines. Otherwise, it's just doing the same thing as efficient as the other, but with different syntax.

  22. #47
    SitePoint Evangelist catweasel's Avatar
    Join Date
    Apr 2007
    Location
    Goldfields, VIC, Australia
    Posts
    518
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kon-Tiki View Post
    Catweasel: Here's one I wrote the other day:
    As Arkinstall has pointed out.. you've written a function to write one specific form.. if you need another form you're going to have to write another function. With the class that I've posted I can dynamically created forms on the fly with the one class. I've just done a site with 8 different forms (some of them enormous) submitting data to 8 different tables and I use the one class to handle all forms on the site. Doing it your way I think I'd be writing 20 times the number of code lines.

  23. #48
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    not required to write more than one or two lines for forms that would otherwise be 50 lines
    I don't see it as the amount of lines, it's the amount of data you need. For example, a form class with defined defaults would allow you to write:
    PHP Code:
    <?
    $form 
    = new Form();
    ?>
    instead of having to define the form method, action and optionally enctype.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  24. #49
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    For build SQL queries using that class I had an idea instead of setting up parameters or anything like that could set up a way to use like a pseudo array to make it. But this array would need to be fixed size for its keys.

    Code:
    [
        SELECT, field,
          FROM, table,
         WHERE, field, value,
         ORDER, field, direction,
         LIMIT, min, max
    ]
    
    // OR multi fields
    
    [
        SELECT, [fields],
          FROM, table,
         WHERE, [expressions], null,
         ORDER, [items], null,
         LIMIT, min, max
    ]
    so for example..
    PHP Code:
    define('SELECT',  1);
    define('FROM',    2);
    define('WHERE',   4);
    define('ORDER',   8);
    define('LIMIT',  16);

    function 
    build () {

        
    $args func_get_args();
        
    $num  func_num_args();

        for (
    $i 0$i $num$i++) {
            switch (
    $args[$i]) {
                case 
    SELECT:
                    
    // Its a SELECT, put out the tables and advance by one.
                    
    $i += 1; continue;
                break;
                case 
    FROM:
                    
    // Table advance by one.
                    
    $i += 1; continue;
                break;
                case 
    WHERE:
                    
    // advance by two.
                    
    $i += 2; continue;
                break;
                
    // and so on.
            
    }
        }

    }

    build(SELCET, array('field1''field2'), FROM'table'WHERE'fieldB''matchme'ORDER'col'ASCLIMIT5null); 
    Not saying this is the best way to go just throwing ideas around.
    In fact I got this from another language that I'm working with (LSL.)
    http://www.lslwiki.net/lslwiki/wakka...rimitiveParams
    The scripting language used within Second Life.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.



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
  •