SitePoint Sponsor

User Tag List

Results 1 to 23 of 23
  1. #1
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)

    Lazy coding - efficiency functions

    After getting thoroughly fed up with typeing $_POST, $_GET, $_SESSION etc I wrote some lazy functions to save typing!

    PHP Code:
    function P($var) {
        return 
    $_POST[$var];
    }

    function 
    G($var) {
        return 
    $_GET[$var];
    }

    function 
    R($var) {
        return 
    $_REQUEST[$var];
    }

    function 
    S($var) {
        return 
    $_SESSION[$var];
    }

    // usage:
    // assuming you have a form with an input called myFieldName 
    echo P('myFieldName');
    echo 
    R('myFieldName'); 
    how lazy is that?!
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  2. #2
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, must help on typing. One more for cookie:
    Code php:
    function C($var) {
        return $_COOKIE[$var];
    }

    Lol!
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  3. #3
    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)

    Talking

    Nice one! What about this:
    PHP Code:
    function make_life_easy(){
       
    $p =& $_POST;
       
    $g =& $_GET;
       
    $r =& $_REQUEST;
       
    $s =& $_SESSION;
    }
    function 
    P($var) {
        return 
    $_POST[$var];
    }

    function 
    G($var) {
        return 
    $_GET[$var];
    }

    function 
    R($var) {
        return 
    $_REQUEST[$var];
    }

    function 
    S($var) {
        return 
    $_SESSION[$var];
    }
    echo 
    P('myFieldName');
    echo 
    R('myFieldName');
    //or, if you want to fetch the whole array:
    make_life_easy();
    print_r($p); 
    or, even better:
    PHP Code:
    <?
    function make_life_easy($scale){
       if(
    $scale <= 1){
          
    winning_lottery_ticket->send($me);
       }else{
          
    bill_gates_inheritance->send($me);
          
    order_assassin(&$bill);
       }
    }
    make_life_easy(2);
    ?>
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  4. #4
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    so it's not just me!

    One for the javascript.....
    Code:
    function $(id){
        return document.getElementById(id);
    }
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  5. #5
    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)
    did you take that from jquery?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  6. #6
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    No, it forms part of an AJAX routine for separating GET and POST queries so that I can reuse the same methods etc for any form.

    It's what gave me the thought of the php functions
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  7. #7
    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)
    ah - handy.

    Hey, I've always wondered, how did you make that cool Avatar?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  8. #8
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    Photoshop - using the pen tool, alot of patience and a few layers
    Each spike is individually 'pulled' out of the original vector circle with points and the eyes have 3 different vector layers as well!
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  9. #9
    SitePoint Addict
    Join Date
    Apr 2005
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you have to type it more than once? Put it into a function, thats my rule
    How does that make your feel?

  10. #10
    Obey the Purebreed trib4lmaniac's Avatar
    Join Date
    Dec 2004
    Location
    Cornwall, UK
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't think I'd ever use these functions, but the most annoying thing about superglobals is checking whether an item exists.
    PHP Code:
    function P($var) {
        return isset(
    $_POST[$var]) ? $_POST[$var] : null;

    And don't forget about convenience functions like filter_input provided for you by the PHP team.

  11. #11
    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's being improved in PHP6 - you'll only need to do:
    PHP Code:
    $var = isset($_POST['var']) ?: null
    You can still assign values to the first field if you want, though.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  12. #12
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    extract($_POSTEXTR_PREFIX_ALL'p');
    extract($_GETEXTR_PREFIX_ALL'g');
    extract($_SESSIONEXTR_PREFIX_ALL's');

    $g_somequerykey;
    $s_mysession;
    $p_postage
    :P
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  13. #13
    Obey the Purebreed trib4lmaniac's Avatar
    Join Date
    Dec 2004
    Location
    Cornwall, UK
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by logic_earth View Post
    PHP Code:
    extract($_POSTEXTR_PREFIX_ALL'p');
    extract($_GETEXTR_PREFIX_ALL'g');
    extract($_SESSIONEXTR_PREFIX_ALL's');

    $g_somequerykey;
    $s_mysession;
    $p_postage
    :P
    It's like register_globals all over again

  14. #14
    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 really, just don't have variables begining with $p_ in ordinary code. No real security risk, I think.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  15. #15
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    A couple of years ago I found this class, part of this framework in phpclasses, and I adapted it slightly.

    So I just do :

    PHP Code:
    $g->['name']; 
    and it gives me a sanitized and frisked GET value. ($p-> = POST value etc)

    Then I got vim to expand $g to $g->['|'] as I type.

    i.e. $g->['<blinking cursor here>']
    PHP Code:
    // a class which basically does this:
        
    if(isset($_GET)    && !isset($this->g)) $this->this->sanitize($_GET,true);
    // where sanitize makes sure there is nothing nasty in it. 
    I am unsure of the performance hit, but it sure is easy to use.

    There is a similar inbuilt function in PHP now, but am not exactly sure of the name of it or maybe its still a PECL extension ...
    Edit:

    .. sorry, I meant an inbuilt function that will sanitize input variables


    Found it, www.php.net/filter
    Last edited by Cups; Oct 12, 2007 at 07:37. Reason: clarification

  16. #16
    SitePoint Wizard TheRedDevil's Avatar
    Join Date
    Sep 2004
    Location
    Norway
    Posts
    1,191
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    I used a similar static class to allow me to type less a few years ago.

    Though these days I really prefer readability over "lazy" coding. I will rather type 20 more characters and get a code I can scan in a second and know exactly what it does, than to use lots of classes to save me type a few characters.

    I type fast enough anyway, so when looking on the large picture. I actually save time by typing everything, as what usally takes time is reading over code you created earlier to improve or bug fix.

  17. #17
    SitePoint Addict CVPer's Avatar
    Join Date
    Sep 2007
    Location
    Vancouver, BC, Canada
    Posts
    233
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    agree with TheRedDevil.

    variables starting with $_ are called superglobals which can be used anywhere and anytime.
    using wrapper functions of them will limit the scope of them and reduce the usabilities and increase coherence of your code or products.

    another concern is that using commonly accepted things will be the best choice, especially in the case working in a team or writing library classes and functions. some editors with auto-completion function will help a lot. for example, eclipse.
    * @location Vancouver, BC, Canada
    * @name Steve
    * @job PHP/MySQL, Drupal, WordPress Developer

  18. #18
    SitePoint Addict tbakerisageek's Avatar
    Join Date
    Sep 2006
    Posts
    213
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by TheRedDevil View Post
    I used a similar static class to allow me to type less a few years ago.

    Though these days I really prefer readability over "lazy" coding. I will rather type 20 more characters and get a code I can scan in a second and know exactly what it does, than to use lots of classes to save me type a few characters.

    I type fast enough anyway, so when looking on the large picture. I actually save time by typing everything, as what usally takes time is reading over code you created earlier to improve or bug fix.
    I choose readability over shortcut any day. I do use a nice little form element generation class (Well, Its all procedural) that I can't live without now!!!

    PHP Code:
        //input type text
        
    function input_text($id,$labelName,$labelClass='',$formClass='',$defaultValue='',$maxLength='255',$override=''){
            
    $functionValue = ($defaultValue == '') ? '' ' value="'.$defaultValue.'"';
            
    $functionFormClass = ($formClass == '') ? '' 'class="'.$formClass.'" ';
            
    $functionLabelClass = ($labelClass == '') ? '' ' class="'.$labelClass.'"';
            
            echo 
    '<label for="'.$id.'"'.$functionLabelClass.'>'.$labelName.'</label>';
            echo 
    '<input type="text" '.$functionFormClass.'name="'.$id.'" id="'.$id.'" maxlength="'.$maxLength.'"'.$functionValue.' '.$override.' /><br />';
        
        }
        
        
    //input type Password
        
    function input_password($id,$labelName,$labelClass='',$formClass='',$maxLength='255',$override=''){
            
    $functionFormClass = ($formClass == '') ? '' 'class="'.$formClass.'" ';
            
    $functionLabelClass = ($labelClass == '') ? '' ' class="'.$labelClass.'"';
            
            echo 
    '<label for="'.$id.'"'.$functionLabelClass.'>'.$labelName.'</label>';
            echo 
    '<input type="password" '.$functionFormClass.'name="'.$id.'" id="'.$id.'" maxlength="'.$maxLength.'" '.$override.' /><br />';
        }
        
        
        
    //Text Area Input
        
    function input_textarea($id,$labelName,$labelClass='',$formClass='',$defaultValue='',$override=''){
            
    $functionCSSClass = ($cssClass == '') ? '' ' class="'.$cssClass.'"';
            
            echo 
    '<label for="'.$id.'"'.$functionCSSClass.'>'.$labelName.'</label>
                <textarea name="'
    .$id.'" id="'.$id.'"'.$override.'>'.$defaultValue.'</textarea>';
        }
        
        
    //Input type Checkbox
        
    function input_checkbox($id$labelName$labelClass=''$formClass='',$checked='',$labelFirst='no',$override=''){
            
    $functionFormClass = ($formClass == '') ? '' 'class="'.$formClass.'" ';
            
    $functionLabelClass = ($labelClass == '') ? '' ' class="'.$labelClass.'"';
            
    $functionChecked = ($checked == '') ? '' ' checked="checked" ';
            
            if(
    $labelFirst == 'no'){
                echo 
    '<input type="checkbox" '.$functionFormClass.'id="'.$id.'" name="'.$id.'"'.$functionChecked.$override.'/>';
                echo 
    '<label'.$functionLabelClass.' for="'.$id.'">'.$labelName.'</label>';
            }else{
                echo 
    '<label'.$functionLabelClass.' for="'.$id.'">'.$labelName.'</label>';
                echo 
    '<input type="checkbox" '.$functionFormClass.'id="'.$id.'" name="'.$id.'"'.$functionChecked.$override.'/>';
            }
            echo 
    '<br />';
        }
        
        
        
    //Submit Button
        
    function input_submit($id$buttonLabel){
            echo 
    '<input class="button" type="submit" name="'.$id.'" value="'.$buttonLabel.'" />';
        } 
    It saves me SOOOOOOOO much time and best of all it ensures consistency in how I "Write" my forms...

    I have a few more portions that might not make sense to post here in my Forms Class that will create common Select boxes that include things like States, Number Ranges, etc... and that take an array as input and use the Key as the "Value" ofthe select while using the Value of the array as the Displayed choice.

  19. #19
    SitePoint Addict CVPer's Avatar
    Join Date
    Sep 2007
    Location
    Vancouver, BC, Canada
    Posts
    233
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    nice code, tbakerisageek!

    my form class is in a lit bit different style from yours. i pass the attributes of input tags by arrays.
    PHP Code:
    class Form {
        function 
    input_text($name$label null$options = array(), $is_return false) {
            
    $html_str '';
            
            if (
    $label != null) {
                
    $html_str .= "<label for=\"{$name}\">{$label}</label>";
            }
            
            
    $html_str .= "<input type=\"text\" name=\"{$name}\"";
            foreach (
    $options as $attr_name => $attr_value) {
                
    $html_str .= {$attr_name}=\"{$attr_value}\"";
            }
            
    $html_str .= " /><br />\n";
            
            if (
    $is_return) {
                return 
    $html_str;
            }
            else {
                echo 
    $html_str;
            }
        }
        
        
    // other functions

    to use the funciton, like this
    PHP Code:
    Form::input_text('userid''User Id', array('value' => '000001')); 
    i also found the last parameter pretty handy.
    * @location Vancouver, BC, Canada
    * @name Steve
    * @job PHP/MySQL, Drupal, WordPress Developer

  20. #20
    SitePoint Addict tbakerisageek's Avatar
    Join Date
    Sep 2006
    Posts
    213
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by CVPer View Post
    nice code, tbakerisageek!

    i also found the last parameter pretty handy.
    Thanks, It's proven nice to use. It has evolved to what it is over the last 3 projects I've completed being 90% rewritten each time.

    If you look at the last parameter of my functions, it is an override that you can enter anything you want and it will be appended to the back end of the form element before being closed. I've used this before to add a style="width: 10px;" or something similar. I used to have just about every possible variable as a paramater but didn't want to continue doing it that way after seeing that it was WAY to cumbersome.

  21. #21
    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)
    Personally, I like the way Logic_Earth did the form class.
    It's not static, and it acts as a factory for each element.

    Say, Logic, Hows that class getting on?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  22. #22
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by CVPer View Post
    using wrapper functions of them will limit the scope of them and reduce the usabilities and increase coherence of your code or products.
    yeah, but then using a sanitize() function wrapping a good many of your calls to superglobals also makes things messy ...

    Quote Originally Posted by CVPer View Post
    another concern is that using commonly accepted things will be the best choice, especially in the case working in a team or writing library classes and functions. some editors with auto-completion function will help a lot. for example, eclipse.
    I must admit though, you've got a point, I must have moved on a ways because I was only using that wrapper in mostly procedural code (procedural pages that joined up lots of objects actually). Now I tend to typecast, use framework filtering tools and things like prepared statements to do a lot of my filtering.
    Off Topic:

    When I was a child I thought like a child ...


    Form makers, about the time I started using the wrapper above, I came out with a form class too. That is sooooo wrong too. But still, its saved me hours and hours ...
    PHP Code:
    // create a form post back to itself post method optional db connector
    $form = new formInput("pageForm",$c->s[PHP_SELF],0,$s->var_get("yourdb"));

    // then create a drop list from a db entry - preselected to $next_no
    $form->ListboxMatch(1,"item_head","select id, name from people",$next_no);

    //a text box, label, size length and optional countdowner 'you have 55 chars left' etc
    $form->text('Add a new entry (max 255 chars)''new_min_head','60','255','','counter4');

    // and an array of submit options
    // jsnotNullSubmit ( provide an array of ids that must not be null )
    // plain submits
    // and like this - calling a named js validator
    $form->jsSubmit('go','Save changes >>','min_text','/_scripts/_refresh.js');

    //_refresh.js A 3 line script that must return true for the form to be submitted. 

  23. #23
    . 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 arkinstall View Post
    Say, Logic, Hows that class getting on?
    It coming together a little slower then it was x.x
    Messing with a feel ideas I had see how well they work.

    Hmm so when I get back to where I was I'll post an updated.
    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
  •