SitePoint Sponsor

User Tag List

Results 1 to 10 of 10
  1. #1
    Resident OCD goofball! bronze trophy Serenarules's Avatar
    Join Date
    Dec 2002
    Posts
    1,911
    Mentioned
    26 Post(s)
    Tagged
    0 Thread(s)

    More (hopefully simple) MVC questions.

    I have a few last question to ask before I can consider my MVC understanding complete.

    1) After creating all my classes, and including functions that operate only only that classes datamembers, and no other, I am left with about 10 generic functions. What do I do with them?

    A) Leave them as standalones in a functions.php file?

    + Easily included.
    + Easily ported.
    - Not object oriented.
    - Breaks my file naming strategy.

    B) Make them static functions in a class object?

    + Works with autoload (debated below).
    + Groups consts into more manageable units.
    - I have to update all calls using Class::function()
    - Classes require more resources to instantiate, even if static.

    2) I put all common classes into a single file and include that outright. These include the applications controllers, filters and base classes for commands, requests and views, as well as a few utility classes. My include folder looks like this:

    includes/common.php
    includes/repository/commands/*Command.class.php (* Specialized command)
    includes/repository/requests/*Request.class.php (* Specialized request)
    includes/repository/view/*View.class.php (* Specialized view)

    All stock stuff is included by default, but I need a way to handle third party addons, which in reality shouldn't total that many. The plugins drop their commands, requests and views into the right folders.

    Which of these should I do?

    A) Use autload to catch all addon code?

    + Simple and relatively quick.
    + No need to modify existing code when a plugin is added.
    - More file reads (how many is unknown but expected to be low)

    B) Put all of a particular plugins classes into a single file, and add a Plugin registry to the base app, which loads all plugins and initializes things by calling a new Registrant class in the plugin code?

    + Less file reads.
    - More code than I really wanted, but can live with it.
    - Loads classes that may, or may not be used.
    - Bigger plugin files and an extra class.

    Ok, let's get through these and I'll see if there's anything else I need to ask. Thanks in advance for your comments and opinions.

  2. #2
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Serenarules
    A) Leave them as standalones in a functions.php file?

    + Easily included.
    + Easily ported.
    - Not object oriented.
    - Breaks my file naming strategy.
    Easily included. - RIGHT
    Easily ported. - RIGHT
    Not OO - RIGHT, but they are to be used globally, so => WRONG
    Breaks my file naming strategy - RIGHT, but usually the file naming strategy is not so important, as the class naming conventions.

  3. #3
    Resident OCD goofball! bronze trophy Serenarules's Avatar
    Join Date
    Dec 2002
    Posts
    1,911
    Mentioned
    26 Post(s)
    Tagged
    0 Thread(s)
    Sorry, I'm having problems understanding if RIGHT is being said in a sarcastic way or not. I will assume not as I'm an optimist. To be sure though, if this were your app, you'd include a procedural file?

  4. #4
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Serenarules
    Sorry, I'm having problems understanding if RIGHT is being said in a sarcastic way or not. I will assume not as I'm an optimist. To be sure though, if this were your app, you'd include a procedural file?
    I think REMIYA is sugessting you to use the option A, and I whole heartedly agree. With an already overcrowded global namespace in PHP, a few more functions are not a problem, especially if they really are used globally.

    PHP is not Java, where everything has to be in one class or another. Use the language to its best.

    (Note: I'm not saying that Java's approach is wrong or inferior to PHP's -- they're just different.)

  5. #5
    SitePoint Addict
    Join Date
    May 2003
    Location
    The Netherlands
    Posts
    391
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I agree with BerislavLopac. IIRC there are about 1500 defined functions available in PHP. Take a look at the function overview. I don't think using a bunch of your own would really break nor hurt any concept at all, specially when they're not related to any concrete object in your application.
    There’s more than one way to skin a cat.

  6. #6
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Serenarules
    Sorry, I'm having problems understanding if RIGHT is being said in a sarcastic way or not. I will assume not as I'm an optimist. To be sure though, if this were your app, you'd include a procedural file?
    Sarcasm has nothing to do right here!

    Well, I'd include procedural file, for some reasons. Let me take for example the String functions in PHP. They are all procedural. What if I want to make a new functon for it? Do I have to make a new class (i.e. myString), and then attach the new function as a method to that class? Of course not? Instead of making my programming easier, it would just slow it unnecesarily down.

    A quick example:
    1. A function I needed later was to check the ending of a string. So I created a new function ends_with(string str, string ending).
    2. I placed it in a file called string.functions.php.
    3. Now I just include it with require_once('string.functions.php'); and the function is ready to be used as any build-in php function.

    Some other useful functions inside the file, are is_valid_email(string str), starts_with(string str, string ending), is_valid_php(string str), etc.

    You may call the file also: string.lib.php

  7. #7
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have a "functions.inc.php" which includes all procedural functions I regularly use. Some are mine, some are taken from others, and some were originally by others but improved by me.

    Here it is, hopefully somepne might find some of the functions useful:

    PHP Code:
    <?php

    // ------------------------------------------------------------------
    // STRING MANIPULATION FUNCTIONS
    // ------------------------------------------------------------------

    /**
     * Converts plain text into correct XHTML, changing newlines to &lt;br /&gt; and double newlines to paragraph marks.
     * @param    $pee    String to be converted.
     * @return    Converted string.
     * @author    Matthew Mullenweg    m@mullenweg.com
     */
    function auto_p($pee$br true) {
        
    $pee preg_replace("/(\r\n|\n|\r)/""\n"$pee);                    // cross-platform newlines
        
    $pee preg_replace("/\n\n+/""\n\n"$pee);                         // take care of duplicates
        
    $pee preg_replace('/\n?(.+?)(\n\n|\z)/s'"<p>$1</p>\n"$pee);     // make paragraphs, including one at the end
        
    $pee preg_replace('/<p>(<(?:table|[ou]l|pre|select|form|blockquote)>)/'"$1"$pee);
        
    $pee preg_replace('!(</?(?:table|[ou]l|pre|select|form|blockquote)>)</p>!'"$1"$pee);
        if(
    $br) {
            
    $pee preg_replace('|(?<!</p>)\s*\n|'"<br />\n"$pee);         // optionally make line breaks
        
    }
        
    $pee preg_replace('!(</(?:table|[ou]l|pre|select|form|blockquote)>)<br />!'"$1"$pee);
        
    $pee str_replace('<p><p>''<p>'$pee);
        
    $pee str_replace('</p></p>''</p>'$pee);
        return 
    $pee;
    }


    /**
     * Converts all undescore (_) characters in a string to spaces.
     * @param   $string     String to be converted.
     * @return  String with converted characters.
     */
    function ul2sp($string)
    {
        return 
    str_replace('_'' '$string);
    }

    /**
     * Converts all space characters in a string to underscores (_).
     * @param   $string     String to be converted.
     * @return  String with converted characters.
     */
    function sp2ul($string)
    {
        return 
    str_replace(' ''_'$string);
    }

    /**
     * Converts double quotes (") to HTML entity (&quot;).
     * @param   $string     String to be converted.
     * @return  String with converted characters.
     */
    function htmlquot($string)
    {
        return 
    str_replace('"''&quot;'$string);
    }

    /**
     * Extracts the extension from the given string.
     * Extension is any characters after the final dot.
     * @param   $string     String (usually a filename or path) from which to extract the extension.
     * @return  String containing the extension.
     */
    function ext($string)
    {
        return 
    strtolower(substr($stringstrrpos($string'.') + 1));
    }

    // ------------------------------------------------------------------
    // ARRAY MANIPULATION FUNCTIONS
    // ------------------------------------------------------------------

    /**
     * Returns a transposed two-dimensional array (rows to cols and vise versa).
     * @param   $array  Two-dimensional array to be transposed.
     * @return  Array
     */
    function array_transpose($array)
    {
        
    $result = array();
        foreach(
    $array as $keymaster => $value) {
            foreach(
    $value as $key => $element) {
                
    $result[$key][$keymaster] = $element;
            }
        }
        return 
    $result;
    }

    /**
    * Function to sort an "array of rows" by its columns.
    * Extracts the columns to be sorted and then uses eval to flexibly apply the standard
    * array_multisort function.
    *
    * Uses a temporary copy of the array with "_" prefixed to the keys. This makes sure that
    * array_multisort is working with an associative array with string type keys, which in turn
    * ensures that the keys will be preserved.
    *
    * TODO: find a way of modifying the keys of $array directly, without using
    * a copy of the array.
    *
    * Flexible syntax:
    *     <code>$new_array = arrayColumnSort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...);</code>
    *
    * Original code credited to Ichier (www.ichier.de) here:
    *     http://uk.php.net/manual/en/function.array-multisort.php
    *
    * Prefixing array indices with "_" idea credit to steve at mg-rover dot org, also here:
    *     http://uk.php.net/manual/en/function.array-multisort.php
    *
    * @param    Mixed    Variable number of arrays and/or sort flags may be passed as parameters.
    * @return    Array sorted by columns.
    */
    function array_column_sort()
    {
        
    $args func_get_args();
        
    $array array_shift($args);
        
    /*
            Make a temporary copy of array for which will fix the
            keys to be strings, so that array_multisort() doesn't
            destroy them.
        */
        
    $array_mod = array();
        foreach (
    $array as $key => $value) {
            
    $array_mod['_' $key] = $value;
        }
        
    $i 0;
        
    $multi_sort_line "return array_multisort( ";
        foreach (
    $args as $arg) {
            
    $i++;
            if (
    is_string($arg)) {
                foreach (
    $array_mod as $row_key => $row) {
                    
    $sort_array[$i][] = $row[$arg];
                }
            }
            else {
                
    $sort_array[$i] = $arg;
            }
            
    $multi_sort_line .= "\$sort_array[" $i "], ";
        }
        
    $multi_sort_line .= "\$array_mod );";
        eval(
    $multi_sort_line);
        
    // now copy $array_mod back into $array, stripping off the "_"
        // that we added earlier.
        
    $array = array();
        foreach (
    $array_mod as $key => $value) {
            
    $arraysubstr($key1) ] = $value;
        }
        return 
    $array;
    }

    // ------------------------------------------------------------------
    // MISCELLANEOUS FUNCTIONS
    // ------------------------------------------------------------------

    /**
     * Redirects the client to a new URL using HTTP header.
     * @param   $url    String containing the URL to redirect to.
     */
    function redirect($url)
    {
        
    header("Location: $url");
        exit;
    }

    /**
     * Returns a number of bytes from the upload_max_filesize directive.
     * @return    Integer        Maximum size of uploadable files, in bytes.
     */
    function get_upload_max_filesize()
    {
        
    $size ini_get('upload_max_filesize');
        
    $num = (int) $size;
        if(
    preg_match('/m/i'$size)) {
            return 
    $num 1024 1024;
        }
        else if(
    preg_match('/k/i'$size)) {
            return 
    $num 1024;
        }
        else {
            return 
    $num;
        }
    }

    /**
     * Takes the fields of a HTML form and sends them to the given address.
     * The fields are formatted as "field_name: field_contents", with each field on a new line.
     * Any underscores in the field names are converted to spaces.
     * @param    $to            String containing the email address to send the form to.
     *                         Multiple addresses may be separated by a comma, just as per the mail() function.
     * @param    $subject    String containing the subject of the mail message.
     * @param    $fields        Associative array, usually $_POST or $_REQUEST,
     *                         having field names as keys and contents as values.
     *                      If a field contains multiple values (i.e. is an array), the values
     *                      are separated by a comma.
     * @param    $skip        Array of field names that are not to be included in the mail.
     * @param    $headers    String or array containing the additional headers.
     *                         If an array, the headers should be defined as "header_name => header_value".
     *                      If a string, the headers should be written as "header_name: header_value\r\n".
     * @return    Boolean        Return of the mail() function.
     */
    function send_mailform($to$subject$fields$skip false$headers '') {
        
    $skip $skip $skip : array();
        
    $message "$subject\n----------------------------------------------------------\n\n";
        foreach(
    $fields as $field => $value) {
            if(!
    in_array($field$skip)) {
                
    $value is_array($value) ? implode(", "$value) : $value;
                
    $message .= ul2sp($field) .": $value\n";
            }
        }
        
    $header_string '';
        if(
    is_array($headers)) {
            foreach(
    $headers as $header => $contents) {
                
    $header_string .= "$header$contents\r\n";
            }
        }
        else {
            
    $header_string $headers;
        }
        return 
    mail($to$subject$message$header_string);
    }

    /**
     * Simulates the <code>getallheaders()</code> function in environments other than Apache.
     * @return    Array of HTTP request headers.
     */
    if(!function_exists('getallheaders')) {
        function 
    getallheaders() {
            foreach(
    $_SERVER as $h => $v)
                if(
    ereg('HTTP_(.+)',$h,$hp)) {
                    
    $headers[$hp[1]]=$v;
                }
            return 
    $headers;
        }
    }

    ?>
    With all the OOP going around, we sometimes forget the usefulness of the PHP basics.

  8. #8
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow
    The function redirect($url) is very good, I find it very useful. Perhaps we should combine and put all the useful functions in one global file.

  9. #9
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sure, send yours in.

  10. #10
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is one of the functions, that I use in almost every application:
    PHP Code:
     <?
    // USAGE: if(get_magic_quotes_gpc()){unescape_globals();} 
     
    //==================== START OF FUNCTION =======================//
    //  FUNCTION: private_unescape                                 //
    //=============================================================//
        /**
         * Unescapes an escaped variable.
         */
    function private_unescape($v){
        return 
    is_array($v) ? array_map('private_unescape'$v) : stripslashes($v);
    }
    //=============================================================//
    // FUNCTION: private_unescape                                 //
    //====================== END OF FUNCTION ========================//
     
    //===================== START OF FUNCTION =======================//
    //  FUNCTION: unescape_globals                                 //
    //=============================================================//
        /**
         * Unescapes all the global variables POSTs, GETs, REQUESTs, COOKIEs
         */
    function unescape_globals(){
        foreach (array(
    'POST''GET''REQUEST''COOKIE') as $gpc){
            
    $GLOBALS["_$gpc"] = array_map('private_unescape'$GLOBALS["_$gpc"]);
        }
    }
    //=============================================================//
    // FUNCTION: unescape_globals                                 //
    //====================== END OF FUNCTION =======================//
    ?>
    Example Usage:

    PHP Code:
    <?php
    // 1. Including the include file
    require_once('include/unescape_globals.function.php'); 
     
    // 2. Calling the unescape function
    if(get_magic_quotes_gpc()){unescape_globals();}
     
    // 3. Now we can use all the global variables, without running into troubles
    ?>


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
  •