I've been browsing and perusing the forums a lot over the past week or so, and have come to see some pretty amazing and intriguing concepts coded or introduced in PHP. I'm not sure whether this belongs in PHP 5 or not (because I don't know if these concepts apply to PHP 5 only), but here's a few questions I've compiled and been wanting to get the answers to for a while, because they seem like things which can help me with my coding later on:

  1. What is a "database abstraction layer"? What can it do for me? What are the advantages of it? Do I have to write it myself?

  2. What is the purpose of "Smarty"? I thought LAMP was a 3-tiered system - the database, the PHP (logic) processor, and the HTML/CSS for presentation. With Smarty, has it become a 4-tiered system? Or is Smarty a second/alternative method of presenting data? Does it give me any advantages?

  3. How does caching work in PHP? How can I implement it?

I realize these are complex questions with probably lengthy or in-depth answers, so I won't mind if you point me to some great tutorials or discussions on these topics.

Thanks in advance! 🙂

    A database abstraction layer could refer to a class written to put an extra layer between the programmer and the dbms being used. One may actually be capable of communicating with multiple database engines (mysql, postgresql, oracle, mssql) but to the programmer all the function calls used are the same. The new class may provide with functions like insertData, updateData, getNextRecord or something like that, so it doesnt matter what db engine is used, the class still only requires you to use the same functions, as opposed to having to remember how to call the mysql mssql ora and pg functions.

    Smarty is just a powerful template engine used to separate the design part from the coding part. On smarty's site they have a pretty good explanation of why to use it: http://smarty.php.net/whyuse.php

    As far as caching, im not too sure what you mean by that. It is possible to actually compile php scripts into bytecode to be run by the zend optimizer. since these scripts are precompiled you have increased performance and speed since the same script doesnt need to be parsed and interpereted every time the script is called.

      Thanks for the info on DAL and Smarty.

      About caching, I meant that PHP can query a DB for info and "remember" what the DB's data was, so later on, when another user requests the same page, it doesn't have to re-query the DB.

        For compiling / script caching see http://phpmailer.sourceforge.net/faq.html as it has a list 1/2 way down the page.

        You don't have to write a db layer youself, but I did, as I wasn't aware of PEAR or any of that guff. Basically I don't have to worry about error handling and bleedin' query results and all that as I just do

        $db->safe_query($q); // if query is bad you'll soon know
        
        $row = $db->fetch_assoc();  // oh the joy of typing 6 less characters

        Of course it's just a wrapper around the built in functions, but it all looks a whole lotta lovely and like Planetsim says, if you end up changing your database all your code will still look the same, and probably all work if the SQL dialect the other end speaks your gabble.

        For some situations the Smarty isn't needed when a str_replace of {USERNAME} will do, but like I said in the other thread, sometimes it'll bring you the biggest smile you'll have in months when you realise you've got about 80% of your workload taken from you.

          LoganK wrote:

          About caching, I meant that PHP can query a DB for info and "remember" what the DB's data was, so later on, when another user requests the same page, it doesn't have to re-query the DB.

          sessions

            I think Logan might also be referring to something I said in the smarty loops thread about not having to hit the database if the page is already cached - here's sort of what I do wher $sm is a Smarty object

            if ($sm->is_cached(THIS_TEMPLATE, $currPage))
            {
            	echo 'NO DB CALL - Rah!';
            }
            else          // funcs in here can hit the db real hard, but don't need to be run if it's cached
            {		// DON'T put your db connects at the top of the script as they burn helluva amount of time, and if they're not needed it means you are a plank
            
            require_once('inc/db-connect.php');
            require_once('inc/db-connect-master.php');
            require_once('inc/banned-ad-funcs.php');
            require_once('inc/ad-menu-data.php');
            echo 'YES YES DB CALL - ';
            
            assign_menu_data($sm, $currPage);
            
            if ($currPage != BAD_AD)
            {
            	$wasData = ad_assign_list($currPage, $sm);
            
            	if (!$wasData)
            	{
            		$currPage = BAD_AD;	// to stop false entries filling the cache with muck
            		echo ' NO DATA!!!!!';
            	}
            }
            }
            
            $sm->display(..... , $currPage);   // page is dynamic, so that is given as cache id
            
              devinemke wrote:

              sessions

              I said if another user comes by and requests the same page. Sessions won't do me any good in that case. Drakla had the right idea - that's how Smarty does it, I wanna know how to do it in PHP.

              All of the other info is great guys, thanks!

                You can also cache using a buffer.

                Buffer the whole page, save the "html" as a file.

                Then check the file's modified time, and the current time.

                If it is past a certain point, re-run the php scripts and DB calls.

                Otherwise, just output the generated html file.

                I have alil class I wrote I use for all my projects, I can send it to you if you would like, its kind of small, but not sure if it will fit in this message window

                Works like this...

                //cache timeout
                $cachetimeout = 1; // minutes
                
                //include Cache class
                include_once($local_path . "class/cache.php");
                
                // create unique filename
                $filename=(isset($_SERVER['QUERY_STRING']))?$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']:$_SERVER['PHP_SELF'];
                
                // start cache class
                $cache = new Cache($filename);
                
                // Check to see if we are using the cached file, or generateing a new one
                if($cache->checkcache($cachetimeout)){
                	$cache->readcache();
                }else{
                	$cache->startbuffer();
                	// DB Calls & HTML
                }
                $cache->writecache();
                

                  Interesting idea. Sure, send it to me, I'd love to take a look at it. What do you mean by "buffer" the page?

                    LoganK wrote:

                    1. What is a "database abstraction layer"?
                    - What can it do for me?
                    - What are the advantages of it?
                    - Do I have to write it myself?

                    1. What is the purpose of "Smarty"?
                      ..... is Smarty a second/alternative method of presenting data?
                      ..... Does it give me any advantages?

                    2. How does caching work in PHP? How can I implement it?

                    1. Data Abstraction Layer.
                    Say you have a forum application scipt in PHP. Run by php.exe.
                    And you have an External database program: Oracle.bin
                    You can write your php forum to use Oracle Database data.

                    But if you want to share your forum application script with others.
                    They might use one of like 10 different database programs.
                    That is about how many it is out there. Which are worth to mention.
                    Postgree, mssql, msaccess or whatever their names.

                    ( Iuse only php own capability to store data by creating files.

                    See: [man]fopen[/man] - [man]fwrite[/man] - [man]fread[/man] - [man]fclose[/man]
                    This is also called flat file - or flat text file database technique.

                    So for me is NOT THIS PROBLEM, with adjusting to exrternal programs.
                    My code will work, as is, for anyone with ONLY PHP)

                    Now you can save all functions that 'talks directly' with that database,
                    and have one such set of functions for each database users want to add-on.
                    But in your forum script these functions have same names:
                    create_table( $table_name )
                    add_record( $data_row )
                    delete_record( $id )
                    find_record( $column_name, $value );

                    Now in config.php settings, admin selects a database or database type he wants to use.
                    And php reads settings, and get that set of functions beloninging to that specific database.
                    And NO CHANGES in your forum scipt is needed to run different databases
                    along with your forum.

                    I have more than 100 different PHP Scripts: Forums, CMS, Blogs, Guestbooks
                    and whatver application,
                    that I have downloaded, have had a look at and stored in my PC. For FREE.

                    From this my collection of php scripts,
                    here is a bit of code from such a db-layer (database layer)

                    <?php
                    /*****
                        This is a part of 'common.php' 
                        which can be included by any php page like 'index.php'
                    *****/
                    
                    // get settings for this forum
                    include 'config.php';
                    
                    // get the specific dB layer set of functions
                    // that should be used from: '$dbtype'. '.php'
                    if(!file_exists($config['path']."core/database/".$config['dbtype'].".php"))
                     {
                      // if no valid DB tell user that no valid DB type was found
                      require_once($config['path']."core/includes/nodb.php");
                     }
                    
                     require_once($config['path']."core/database/".$config['dbtype'].".php");
                    
                     $dbconn =& new database($config['dbhost'], $config['dbname'], $config['prefix'],
                                $config['dbuser'], $config['dbpass'], $config['persistent']);
                    
                     // Lets connect to our database
                     if(!$dbconn->connect())
                     {
                      // Was unable to connect to specified DB
                      require_once($config['path']."core/includes/nodb.php");
                     }
                    
                    ?>

                    -----
                    2. Smarty template engine add-on class
                    3. Caching in PHP
                    -----

                    I am sure I could write an easy enough to understand explaination
                    to those 2 issue also.

                    But I am not alone here, to answer questions and to educate people,
                    who want to increase their knowledge in how to get independent from software dealers,
                    and write their own scripts using fairly simple programming language of PHP.
                    I leve it up to my partners here at http://www.phpbuilder.com
                    to try to give you food for your hunger in knowing more.

                    To LoganK
                    from your php friend
                    /halojoy

                    🙂
                    knowledge is an easy burdon, compared to other hardships we have to carry in life

                      I knew this was from halojoy as soon as I saw the big "1." and the formatting of my quote. 😃

                      Thank you for your very informative discussion of all my questions. The DB abstraction was very helpful. FYI, I know all about flat file DB and PHP's file functions - I'm not a n00b 🙂 Plus I've seen your sig - "very fast text file db man". I kinda figured that you like flat-file databases.

                      I'll take a look more around at caching and Smarty. If anyone else has any explanations/discussions/answers on those two, I'd love to hear it!

                      Thanks to all so far!!!

                      // insert philosophical quote like halojoy here

                        LoganK wrote:

                        Thank you for your very informative discussion of all my questions.
                        The DB abstraction was very helpful.
                        FYI, I know all about flat file DB and PHP's file functions
                        - I'm not a n00b
                        🙂

                        I'll take a look more around at caching and Smarty.
                        If anyone else has any explanations/discussions/answers on those two,
                        I'd love to hear it!

                        Thanks to all so far!!!

                        Todays Quote (not a 5-7-5 haiku):
                        Not saying 'Thank You' is a perfect way
                        to avoid help in coming days!
                        This is like your parents taught you.

                        /halojoy 2005

                        A bit on one way to cache.
                        There are many ways to feature caching of webpages.

                        With PHP-Apache-Perl-Databases Easy Install Package:
                        XAMPP or LAMPP
                        which I use for development as well as for my webpaghes, comes 2 extra programs:

                        1. Webalizer - weekly server stats summary in graphics
                        and
                        2. eAccelerator - caches php-pages that are of more static nature

                        This means that it checks if is any diiference in the HTML output from each php page,
                        if not any change, output the cached HTML right away,
                        instead of build HTML up using the php-script of this request.

                        This accelerates the speed with what the visitors browser gets the HTML.
                        Making php being served quicker, than normally.
                        No un-necessary work is beeing done by PHP.
                        Also takes load off server, if have many connections to serve.

                        To get more info on 'PHP Accelerator' - search with google:
                        Keyword string (including quotation marks):
                        "php accelerator"

                        Apache can do some caching of HTML and other pages, too.
                        And also at client, visitor Browser caching can be done (in Temporary Internet pages, History cache)
                        But PHP Accelerator specialize at php server side caching.

                        http://zend.com has one of the best php accelerators there is.
                        But it is not freeware, as far as I know.

                        eAccelerator is freeware to download and install along with your server and PHP
                        And as i said,
                        it is included and automatically installed with XAMPP.

                        XAMPP homepage:
                        Many people know from their own experience that it's not easy
                        to install an Apache web server and
                        it gets harder if you want to add MySQL, PHP and Perl.

                        XAMPP is an easy to install Apache distribution
                        containing MySQL, PHP and Perl.
                        XAMPP is really very easy to install and to use - just download, extract and start.

                        At the moment there are four XAMPP distributions.
                        http://www.apachefriends.org/en/xampp.html

                        http://www.apachefriends.org/en/xampp.html
                        A nice domain name!
                        Apache Friends .org

                        /halojoy - sometimes friendly and sometimes helpful, too

                        😉

                          halojoy wrote:

                          /halojoy - sometimes friendly and sometimes helpful, too

                          Only sometimes? 😃

                          Thanks for re-formatting my post - it looks much nicer! 🙂

                          Thanks for the info about caching - I'll look up on Google for those accelerators. I did some research and found something about "ob_start" and "ob_flush" - know anything about it?

                          I'll keep this topic unresolved for about another day, and then I'll resolve it. I've got a lot of info; I just want to see if anyone else has anything to point out.

                            hi.

                            ob is short for 'Output Buffering"
                            in php.ini settings, you can turn ON and OFF output buffering
                            But even if automatical ob is turned off, you can use is in a php page, php script

                            ob_start();
                            turns output buffering ON.

                            This means, that any echo, or other HTML output from script
                            will NOT be sent to Webserver and visitor browser directly,
                            but instead be written to an Output Buffer

                            When script wants to present this 'HTML source code' that has been built up in buffer,
                            you flush = send it out - at least I think ob_flush() function does this
                            and

                            ob_end(); turns output buffering OFF

                            which makes code now instead being delivered from php script
                            directly to http-server and visitor (client) Browser.
                            And this is the normal operation. Without buffer use.

                            There are advantages with using an Output Buffer to store everything
                            until complete HTML page is ready for display.
                            There might be some disadvantages, too.
                            But if correctly used, it is positive.
                            Many say their website pages loads faster,
                            using ob_start(); or set php.ini output_buffering = ON

                            By default in php.ini I think ob_buffering is set OFF
                            at least this is the setting I use.
                            I can however somtimes use it locally in my scripts.
                            But not often.

                            this was about that

                            I am sure others can add more on this
                            I have not really had any need for studying this any deeper.
                            Most scripts can work quite alright without any output buffering at all.

                            /halojoy - sometimes knows only roughly what it is about
                            and many times this is more than enough

                            😉

                              Using buffering on a page can speed loading if no other systems are already in place in your server to buffer output as you throw the data out all at one time, and not in trickly bits with every echo. Another great trick with ob_start is capturing the output of a function that does printing / echoes like this:

                              ob_start;
                              
                              my_loudmouth_func();  // <-- echoes loads of guff, perhaps I should have called it Halojoy()
                              
                              $out = ob_end_clean(); // now have a variable with a bit old string in it

                                Yeah and so basically you have the whole page buffered, in html.. like looking at the source of the generated file and putting it all into a variable..

                                I'll send you that class code in a PM

                                  So, I can use ob_start() at the beginning to hold all output to a buffer, and then can I use something like "$content = ob_flush();", and then write $contents to a file, and then later on serve that file instead of re-querying the DB and all? Is that what the basics of PHP caching are?

                                  Edit: Didn't notice your post solodesignz. Firefox tab time-lag. I'll check my PM.

                                    You get the contents with [man]ob_get_clean[/man] which also detroys the buffer, or [man]ob_get_contents[/man].

                                    Another simple way of buffering is to use [man]var_export[/man] to write out something like a huge array you've generated from a complex db query because it's in usable php form. Remember if you pass true as the 2nd argument to var_export (or print_r) it returns the data rather than vomiting it out.

                                      Allright, I'll have to remember that. Thanks 🙂

                                      I'm going to leave this as unresolved until 12:30 p.m. (two hours from now).

                                        Write a Reply...