Archive for September, 2007

611Chapter 33Stylefor ($i = $n, $plist = array(); (Free web space)

Monday, September 10th, 2007

611Chapter 33Stylefor ($i = $n, $plist = array(); $i > 1; $i–) if (!$carray[$i]) array_push($plist,$i); return($plist); } Obviously, this implements the Sieve of Erasthones, and $plistis a list of all the prime num- bers less than $n. Obviously. So why do programmers strive for conciseness? The first reason is that it saves them time (butonly at the time of actual code writing). The second reason (and we re only half-joking) is thatthey re afraid some other programmer (probably one trained in C) will come along later, laughat them, and point out that their code could have been written in only half the space. Conciseness tipsIf you must write code that fits in less space, try some of the following techniques. Use return values and side effects at the same timeIt s a very common trick to exploit the fact that the value of an assignment is the valueassigned, as in the following pseudocode: while ($next = GetNextOne()) DoSomethingWith($next); where GetNextOne()is some function that returns useful values in sequence and thenreturns a false value when it runs out of them. When a false value is returned, $nextis false, and the whileloop terminates. Use incrementing and assignment operatorsThe incrementing operators (++and –) shorten statements that involve adding or subtract- ing one from a variable, and the combined assignment operators (+=, *=, .=, and so on) makecertain kinds of assignments more concise. The incrementing operators and the arithmetic assignment operators are covered in Chapter 10, and the combined string assignment operator (.=) is covered in Chapter 8. Often these operators are used in combination with the previous trick, as in: while ($count–) DoSomethingWith($count); which (assuming that $countstarts as a positive integer) would call its function for the verylast time on the value 1. Reuse functionsThis is one case where conciseness is good, because functions are good. If you can identifyany stretches of code that get duplicated in your pages, try to replace each one with a call toa single function that packages up that code. Your code will be shorter by the amount of theduplication and also easier to maintain. Cross- Reference37
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

610Part IIIAdvanced Features and Techniquesto try to identify (Make a web site)

Sunday, September 9th, 2007

610Part IIIAdvanced Features and Techniquesto try to identify a query that is particularly time-consuming. After you ve identified a guiltyquery, there are a host of techniques available to speed that query up, many of which don thave anything to do with PHP. For details on optimizing database-enabled PHP code, see Chapter 18. Focus on the innermost loopLet s say that you have a page with embedded looping constructs, like the following: for ($x = 0; $x < 100; $x++) { do_X(); for ($y = 0; $y < 100; $y++) { do_XY(); for ($z = 0; $z < 100; $z++) { do_XYZ(); } } } Unless you have a really good reason to think otherwise, your optimization focus should beon the function do_XYZ()(which will execute 1,000,000 times) rather than on the other twofunctions (10,000 times and 100 times). Conciseness: The downsideBefore we get into how to write more concise code, let us say that we think conciseness is anoverrated virtue, for the following reasons. Conciseness rarely implies efficiencyAlthough it s true that somewhere in the guts of the PHP engine, the characters of the codeyou write are being consumed one by one (and so, in theory, more code takes more time), inpractice, the Zend-based parsing engine of PHP is so zippy that the number of characters justdoesn t matter. Ditto for the time or space consumed in extra variable assignments or theoverhead of extra function calls. Conciseness trades off with readabilityRemember that every keystroke you omit might be the keystroke that would have let some- one figure out what the heck you were thinking when you wrote the code. For example, takealook at the following admirably concise function: function sieve($n) { for ($i = 2; $i <= sqrt($n); $i++) for ($j = $i, $ind = $i * $j; $ind <= $n; $j++, $ind = $i * $j) $carray[$ind] = 1; Cross- Reference37
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

609Chapter 33StyleEfficiency: (Web design software) Only the algorithm mattersThere was a

Sunday, September 9th, 2007

609Chapter 33StyleEfficiency: Only the algorithm mattersThere was a time when computer memory and computer cycles were so precious that it wasworth a lot of effort to boil down your code to the smallest number of resulting machineinstructions possible. This is still true in certain areas of software development (kernel pro- gramming, graphics libraries), but for most development tasks saving a few instructions or afew K is not worth backing off on any other goal. This is especially true for Web scripting, where there is always going to be some overhead of purely Internet-related execution delay. Ifit takes half a second for a user to fetch your page, regardless of how your page is produced, then an extra five milliseconds on the server side will be lost in the noise. With that said, there s one variety of efficiency that matters and will probably always matter: the broad algorithm or approach that your code uses for a task. For example, if your codelocates a name in a database by querying the database for all names and then doing a stringcomparison for each name to see if it s the one you want, you ll soon find out how much effi- ciency can matter. Efficiency optimization tipsHere are some quick mantras to repeat as you code. Don t reinvent the wheelIt s usually a bad idea to write code that duplicates a language-level facility, unless it s for pur- poses of fun or education. For example, any programmer worth his or her salt should writesorting routines at some point in their education, but no programmer should have to keepwriting them (unless it is actually in their job description). Most high-level programming lan- guages offer some kind of sorting capability (either as part of the language or in a library), and it s very likely that the programmer who wrote them did a better job than you will. PHPisno exception here the array type supports several types of sorting, and most of thedatabases supported by PHP have sorting options built into the query language. Either ofthese options will be faster and more reliable than what you get by rolling your own. Discover the bottleneckAlthough it s good to try to use efficient algorithms from the beginning, it s often not worthdoing other kinds of optimization until you find out that too much of some resource is beingused. At that point, you want to tighten things up, and you ll get the most reward for youreffort if you focus on the piggiest parts of your code. Most code follows the 90/10 rule: 90 per- cent of the time is spent in 10 percent of the code, and you want to locate that 10 percent. One technique that programmers often use to locate that 10 percent is called profiling.A pro- filer is a utility that tracks code as it runs, noting the time spent in every function call, andproducing a neat summary of the results. Unfortunately, at this writing, there is no good gen- eral profiling utility for PHP (although one may be on the way for later versions of PHP). Sothe best bet for now is the poor man s profiling technique: printing the value of the functioncall microtime()in various places in your script to see where the time is going. If the 90/10rule is in effect, the time sink will usually be glaringly obvious. Focus on database queriesAlthough we cover database efficiency in more detail in Chapter 18, you should be aware thatdatabase queries are usually the biggest time sink for PHP sites that have database backends. Especially if your database-enabled site doesn t do a lot of other computationally inten- sive work, your first suspicious glance should be at the queries, and your next task should be37
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

608Part IIIAdvanced (Web hosting domain names) Features and TechniquesUnavailability of servicePHP is

Saturday, September 8th, 2007

608Part IIIAdvanced Features and TechniquesUnavailability of servicePHP is in part a glue language, offering a single environment where a variety of differentcode libraries and external services can be invoked. Any given PHP page might open a file, connect to a database, query an LDAP server, send an HTTP header, or send mail via an SMTPserver. The important habit to develop is covering cases where for some external reason aservice is unavailable, or times out, or behaves oddly, or gets interrupted in the middle. Often, such services have error states that can be retrieved and printed if the only option leftis to informatively die. For example, a reasonable construct for making a connection to amySQL database is: $connection = mysql_connect([arguments]) ordie( Connection failed: $php_errormsg
); This is preferable to the weird and unexpected errors you would see if your code went hap- pily ahead assuming that it had a live database connection. An alternative that is better froma security point of view is: $connection = mysql_connect(…) or error_log($php_errormsg); if (!$connection){ die( Connection Failed ); } because this will avoid displaying interesting facts about your PHP and database configura- tion to the user s browser. Even better style is to use the exception-handling facility introduced in PHP5, rather thansimply failing with die(). Exceptions can be thrown whenever a problematic condition isencountered, and recovered from, at a single point in the code (if you so choose). If it is pos- sible to recover from the problem, exceptions make it easy to structure your code to supportthat. If the script must die anyway, exceptions make it easy to propagate the negative infor- mation and display it at the right time, rather than just aborting execution. Exceptions and exception-handling are covered in detail in Chapter 31. Unexpected variable typesAlthough the type-looseness of PHP is for the most part a good thing, it leaves a little bit ofuncertainty for the programmer about exactly what type a variable or value will turn out tobe. Unless you come to know all the type-conversion rules very well, it can be surprising tohave code that is accustomed to strings suddenly run across a value that is a number, allbecause some PHP construct decided that any string composed only of numerical digits mustreally be a number at heart. One interesting robustness check is to use a text editor to searchyour code for $(thereby finding every variable) and ask yourself for each one what wouldhappen if the type turned out to be surprisingly different. Efficiency and Conciseness Efficiency and conciseness are not the same thing. Efficient code runs using a small amountof execution time or computer memory, while concise code accomplishes a given task in asmall number of lines or keystrokes. In this section, we give some quick tips toward writingefficient and concise PHP code, along with our extremely opinionated commentary about inwhat senses these goals are worth striving for. Cross- Reference37
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Web design - 607Chapter 33Styleload depends on whether you would ever

Friday, September 7th, 2007

607Chapter 33Styleload depends on whether you would ever want that literal block to repeat in your out- put; if not, then the onceversion is probably still what you want. .includecan also be used to assemble complex Web pages from text files instead offrom a database. In some cases, this can even be faster usually when the includeddata is just a sizable text file(s). However, after you go to the trouble to make adatabase connection for any reason, it s probably just as fast to store your big chunksof text there, too. Object wrappersAlthough we haven t covered PHP s object system in detail yet, it s worth noting that consis- tent use of objects can make code more maintainable, much as functions do. For example, some developers of database-enabled PHP sites are disciplined enough to wrap up all of theirdatabase-specific functionality in the methods of an object, so that the rest of their codedoesn t even know what kind of database is supporting the site. In theory, then, if they decideto move from a mySQL database to an Oracle database, only the object-level code will have tobe changed. For details on PHP s support for object-oriented programming, see Chapter 20. Consider using version controlFor large multiprogrammer projects in industrial settings, version control isn t something toconsider it s a must. Similarly, large decentralized open-source projects could not survivewithout CVS(Concurrent Versions System). Even if you are working by yourself or with oneother person on a hobby project, using version control can free you to do more experimenta- tion, secure in the knowledge that you can get to the older versions of your code if somethinggoes awry. See www.cvshome.orgfor more information on CVS. SourceForge also offers free Web-basedCVS project hosting for open-source projects (www.sourceforge.net/). RobustnessThe two commandments of robustness are: .Code should detect unexpected situations and respond gracefully rather than dying. .If code must die, better that it die informatively. Writing robust code is at first a difficult task of imagination, where the programmer tries tothink ahead to all the things that might go wrong and to cover those cases. The ideal situa- tion is for that habit of mind to become a habit of code, so that the coder has a standard setof tests that wrap around the standard potential problems. Although most of the robustnessissues in PHP are the same as in any language, there are two kinds of situations to cover thatare more specific to PHP: problems with an external service, and problems having to do withvariable type. Cross- Reference37
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

Sri lanka web server - 606Part IIIAdvanced Features and Techniquesvariables like $interest_ratebeing passed

Friday, September 7th, 2007

606Part IIIAdvanced Features and Techniquesvariables like $interest_ratebeing passed in as an actual parameter. Finally, some siteswill go so far as to have all their content imported from a database, so that no piece of infor- mation has to ever be changed directly in code. FunctionsHaving tried to maintain a complex site using a Web-scripting language that did not supportfunctions, we can say from our own experience that functions are crucial to maintenance. Theart of procedural abstraction via functions needs a book in itself, but here s some briefadvice: .Always look for opportunities to bundle naked PHP code into a function, especially incases where it might be reused. .Try to keep function definitions short if a definition gets too long, break it up intomultiple functions. .Always load all your function definitions before any code that calls any functions. Include filesOne of the great benefits of dynamic Web page generation over static HTML is the opportu- nity to fight redundancy. Anyone who has ever managed a static site of any size knows howmuch of each file is boilerplate and even editing a single character on each page isn t a pic- nic if your site has 200 pages. PHP makes it very easy to drop anything into your scripts, from one character to a whole sep- arate program, by using the built-in includeor requirefunctions. The syntax is simply: You can also use a variable filename, like this: which will result in the contents of the file Park.incbeing spliced in at the location of theinclude statement. You can use any extension you want for the included file. Popular choices include .txt, .inc, and even .htmlto remind yourself that the file will show up in HTML mode. A few things to remember: .PHP will drop the entire text of the file into your PHP script in HTML mode(asexplained in Chapter 4). If the included file is itself meant to be parsed as PHP, youmust use valid PHP tags at the beginning and end. If any part of the file is meant to beparsed as PHP, you must use valid PHP tags around that section. .Recall the difference between include/requireand include_once/require_once. Ingeneral, if what you are including or requiring is a set of function or class definitions, you should use the oncevariant. If it is straight PHP or HTML, then which variant you37
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

605Chapter 33StyleUniformity (Web design rates) of styleAlthough we have talked in

Thursday, September 6th, 2007

605Chapter 33StyleUniformity of styleAlthough we have talked in a very free and easy way about how all these stylistic choices areup to you, there are situations where it is actually good to have a consensus on what codeshould look like and then enforce that. This is particularly true when many programmers willcontribute code to a project. The reasons that are usually advanced for a uniform style are: .It makes it easier to read code from multiple programmers, because you don t have toget used to a new indenting or layout style every time you see new code. .It makes life easier for version control software (like CVS). If I change a code file thatyou created and my editor changes the indentation, there will be a lot of apparent butspurious differences. The closest thing PHP has to a consensus style is the coding standard developed by the main- tainers of the PEAR project. See Chapter 28 for a discussion of both PEAR and this codingstyle. MaintainabilityMany seasoned programming veterans, especially those who are also managers, tout theimportance of maintainability above that of any other virtue. The problem is, of course, that maintainability is in direct conflict with all the other goals especially speed. When Internet Time gets into the ring with Hypothetical Future CodeMaintenance By Someone Probably Not Myself, everyone knows how the story is going toend. Still, the main mental mantras of maintainability are worth keeping in mind: .The things that are most likely to be changed should be the easiest to find. .Changing those things should not have unpredictable effects. .Each change should have to be made in only one place. Avoid magic numbersA magic numberis a numerical value that might someday have to be changed but is burieddeep in code, often in multiple places. Imagine, for example, these lines of code found in yourbank s hypothetical PHP-based Web site: print( The interest rate on your CD can be as high as5.5%!
); $sample_gains = 5000 * 1.055; print( After a year, a $5000 investment could grow to$$sample_gains!
); Now, when times get tighter and the rate goes down to 5.0 percent, someone has to find andchange every instance of the rate. So, someone does a text search for 5.5, which misses the1.055in the second line here, and now your bank is engaging in false advertising. For simple sites, a better alternative can be as easy using an $interest_ratevariable, whichis assigned very visibly at the top of a script a change in rate means a change only to thatassignment statement. More complex sites might produce their pages as function calls, with37
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

604Part IIIAdvanced Features and TechniquesFeatureHitchcockBirds.htmlMiniseriesIrvinSpy.htmlA dynamic site, on (Web hosting provider)

Wednesday, September 5th, 2007

604Part IIIAdvanced Features and TechniquesFeatureHitchcockBirds.htmlMiniseriesIrvinSpy.htmlA dynamic site, on the other hand might identify the same pages like this: feature.php?ID=1miniseries.php?ID=2In this situation, you can have the best of both worlds: short filename plus unique identifier. (The only downside of this is that some search engines still discriminate against pages withdynamic arguments, under the theory that the contents are likely to change with every pageview and, therefore, won t be worth indexing.) PHP sets no particular limit on the length of variable names. So feel free to invent lengthybutinformative variables like $AddressOfClientCompanyInSasketchewan. Hey, it s yourscript we re just living in it. You only need to be careful if you plan to use a lot of long-namevariables as part of a GET-method form. Underscores versus camelcapsThere are two typical ways to break up long variable and file names in Unix. Underscores looklike this: $name_of_favorite_beerwhereas camelcapslook like this, with the internal capital letters giving the name a humpedprofile: $NameOfFavoriteBeerIt s a purely personal preference, which style you use (unless you have agreed on a particularstyle with your colleagues). PHP itself uses underscores ($PHP_SELF), but this usage by PHPcould be construed as an argument in favor of either scheme for PHP programmers. Justremember you can t use dashes and should be careful with dots. Unix filenames are case sensitive all the time. Filenames in other OSes, such as Windows, arenot case sensitive. If you might be in a position to move PHP files between OSes, be careful. The main thing to strive for here is consistency. It s frustrating to spend a lot of time trying tofigure out why $My_Numberwas never assigned, only to find out that it s because you called it$MyNumberwhen you assigned it. Reassigning variablesSituations arise in which you deliberately want to keep using the same variable name overand over rather than coming up with new names. This happens when you need to be certainonly one variable of a particular type will be valid at any given time. For instance, you mightwant to be sure there can be no confusion about which of two database queries will be usedfor an operation, which you can ensure by using the same name for both (for example, $query). PHP will overwrite the former with the latter, and your variable will always be mintyfresh. Caution37
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

603Chapter 33Styleit (since that (Best web site) is often low priority),

Wednesday, September 5th, 2007

603Chapter 33Styleit (since that is often low priority), but how it stays in sync with the code (which is evenlower priority). When starting a new day job, we have more than once confronted a very com- mon choice: Should we get to know the code by reading the current code itself or by consult- ing some very nicely written documentation of the code as it was two years ago? One approach, used with some languages, is to employ a tool that produces documentationby extracting specially formatted, embedded comments from the code. For example, if youhave followed a given commenting convention, you can point the javadoctool at your Javacode and it will extract class and method comments into a set of HTML pages documentingthe API. This is not a magic solution for the problem of keeping docs in sync with code. (Itwill break down, for example, if people begin writing new methods by copying old methods, and leaving the original comments in place.) But at least developers have to write only onedescription of a given method rather than two. There is an analogous phpdoctool that uses PHP (naturally) to scan PHP code for specialcomments, producing HTML output. If you are doing a large-team project, though, especiallyone making heavy use of object-oriented PHP, you might find phpdocto be helpful. For moreon phpdoc, see www.phpdoc.de/. File and variable namesSome people act like thinking up variable names is equivalent to being forced to write anepicpoem they go into a kind of writer s block and become creatively incapacitated. Forinstance, we once had an intern who was apparently unable to think up a single name or evena halfway decent scheme for doing so. This person s habit was to name every new file accord- ing to simple sequential order: file16.html, file17.html, file18.html, and so forth. Eachvariable on a Web page was called var1, var2, and so on. This story would be a lot funnier ifit had happened to someone else. Because PHP generally requires a lot more variables than HTML, you need a robust namingscheme for all occasions. The following sections include a few tips. Long versus shortLonger is generally better because it s more informative. You can break up long names withunderscores or capitalization if necessary. Even though most filesystems technically allow for long filenames, the results are not prettywhen viewed as icons so GUI users may be consciously or unconsciously averse to usinglong filenames. Icon labels are usually quite short and, thus, naturally lend themselves to veryconcise filenames. Try giving a file a long, complex name (like PoachedPeachesRecipe.php) and putting it on your desktop the result is just viscerally displeasing. Most GUI-oriented filesystems allow and even encourage filenames with spaces in them (forexample, MyDocument.doc). Unix systems do in theory, but in practice it s not such a goodidea. PHP will try to cope gracefully with such filenames, but it may not be able to do so inall situations. One benefit of using PHP for dynamic content generation is that you can use shorter file- names that will be expanded and differentiated by GET-style query strings. For example, astatic site might use this style of filename to uniquely identify each page: Caution37
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

602Part IIIAdvanced Features and TechniquesCommentsPutting comments in code (Windows 2003 server web)

Tuesday, September 4th, 2007

602Part IIIAdvanced Features and TechniquesCommentsPutting comments in code is just like flossing your teeth: important for health and hygiene, the object of many good intentions, all too often skipped just this once, and long regrettedlater if undone. The problem is that there s no immediate glory to be had from commenting all the benefitsare longer term and diffuse. Let s face it: You rarely hear hackers oohing and aahing over thebeautiful commenting of the guy in the next cubicle, and few Web sites go-live dates areallowed to slip so that the programmers can put the finishing touches on their comments. Commenting comes into its own later, when your team leader quits (in the middle of a majorsite redesign) to join a neo-Luddite community; and the rest of you are sitting around scratch- ing your heads and thinking Huh? in unison, as you desperately try to write up some docu- mentation in time for the scheduled release. So what kinds of things should you comment? We feel you mustexplain: .Anything with future what the heck was I thinking? potential (usually due to extremecleverness or extreme ugliness) .Anything you suspect might be a temporary expedient .Anything that will lead to dire consequences if tampered with by ignorant peopleThings that ideally should be noted include: .The date the file was originally created, and the name of the creator .The date the file was most recently altered, the name of the alterer, and possibly anexplanation of the rationale behind the alteration .Any other files or programs that depend on the existence of this file .The intended purpose of the file and of its constituent parts .Things you might want to mention in documentation you re planning to write later .The reason you want to save something that isn t being used (alternate versions, archive copies, and so on), conditions under which it might become okay to throw itaway, or your plans for what to do with itObviously, you re in a better position than we to decide whether these items are strictly nec- essary. If you re using PHP for a very small, purely personal site, maybe commenting wouldbe superfluous, but the bigger and more complex the site, the more you need to annotateyour own work. In theory, it s possible to overcomment, but, in practice, few programmersare guilty of this offense. As we detailed in Chapter 5, there are several styles of PHP comments. Remember that noneof these will be visible from the client machine, even when HTML source is viewed. If youwant client-readable hidden text, you must use HTML comments. PHPDocFor very large and complex programs, code-embedded comments are not sufficient. You wantseparate documentation that someone can read without delving into the code itself. Theproblem with documentation like this, however, is not just how anyone gets the time to writeTip37
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.