1 / 51

Lecture 9 5/3/12

Lecture 9 5/3/12. Arrays and Development Lifecycle. Arrays. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value

lynton
Télécharger la présentation

Lecture 9 5/3/12

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 95/3/12 Arrays and Development Lifecycle

  2. Arrays • There are three different kind of arrays: • Numeric array - An array with a numeric ID key • Associative array - An array where each ID key is associated with a value • Multidimensional array - An array containing one or more arrays

  3. Creating Numeric Arrays • An array is a list variable. It contains multiple elements indexed by numbers or strings • It enables you to store, order and access many values under one name • The array() is useful when you want to assign multiple values to an array at one time e.g. • In this example the ID key is automatically assigned: $users=array(“Bert”, “Harry”, “Betty”);

  4. Continued.. • Access the second element in the array: print “$users[1]”; • Alternatively, you can create a new array using the array identifier: $users[]=“Bert”; $users[]=“Harry”; $users[]=“Betty”;

  5. Adding a new element • Use the array identifier to add new elements to the array: $users=array(“Bert”, “Harry”, “Betty”); $users[]=“Sally”;

  6. Associative Arrays • An array that utilises keys (names) to access values rather than index numbers, making it more friendly to use • Creates an associative array called $ages with three elements: <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>

  7. Example $greetings = array("Irish"=>"Dia Duit", "French"=>"Bonjour", "German"=>"Guten Tag"); print "Hello ". $greetings['French']; Output: Hello Bonjour

  8. Example <?php $character=array ("name"=>"bob", "occupation"=>"superhero", "age"=>30,"special power"=>"x-ray vision"); echo $character["age"]; echo "<br/>"; $character["name"]="bob"; $character["occupation"]="superhero"; $character["age"]=30; $character["special power"]= "x-ray vision"; echo $character["occupation"]; ?>

  9. Multidimensional Arrays • An element in an array could be a value, an object or another array • A multidimensional array is an array of arrays i.e. an array that stores an array in each of its elements: E.g. $array[1][2];

  10. Example

  11. <?php $employees["employee 1"]["name"] = "Dana"; $employees["employee 1"]["title"] = "Owner"; $employees["employee 1"]["salary"] = "$60,000"; $employees["employee 2"]["name"] = "Matt"; $employees["employee 2"]["title"] = "Manager"; $employees["employee 2"]["salary"] = "$40,000"; $employees["employee 3"]["name"] = "Susan"; $employees["employee 3"]["title"] = "Cashier"; $employees["employee 3"]["salary"] = "$30,000"; echo $employees["employee 2"]["name"]. " is the ".$employees["employee 2"]["title"]. " and he earns ".$employees["employee 2"]["salary"]. " a year."; ?>

  12. Accessing Arrays • array_merge(); • array_push(); • array_shift(); • array_slice(); • sort(); • asort(); • ssort();

  13. PHP Functions • Foreach - prints the combined array with a break between each element • count — Count all elements in an array, or properties in an object • print_r() displays information about a variable in a way that's readable by humans

  14. Array_merge() - Accepts two or more arrays and returns a merged array combining all of the elements <?php $first=array("a", "b", "c"); $second=array(1,2,3); $third=array_merge($first, $second); foreach($third as $val) { print "$val<br>"; } ?>

  15. Array_push() - Accepts an array and any number of further parameters each of which is added to the array. Returns the total number of elements in the array <?php $first=array("a", "b", "c"); $total=array_push($first, 1, 2, 3); print "There are $total elements in \$first<p>"; foreach($first as $val) { print "$val<br>"; } ?>

  16. Note • The $first array contains original elements plus three integers we passed to it • Notice we use \$first – we wish to print it as a string not a variable • To print $ we must use \ • Known as escaping a character

  17. Array_shift() Removes and returns the first element of the array passed to it <?php $an_array=array("a", "b", "c"); while (count($an_array)) { $val=array_shift($an_array); print "$val<br>"; print "there are". count($an_array). "elements in \$an_array<br>"; } ?>

  18. Array_slice() - Allows you to extract a chunk of an array. It accepts an array as an argument, a starting position, and a length(optional) <?php $first=array("a", "b", "c", "d", "e", "f"); $second=array_slice($first, 2, 3); foreach($second as $var) { print "$var<br>"; } ?>

  19. Note • The start position is included and three elements are included Hence c d and e

  20. More on Arrays - Sort() • Accepts an array as an argument and sorts it either alphabetically if any strings are present or numerically if all elements are numbers • This function assigns new keys for the elements in the array • Existing keys will be removed

  21. Example <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); sort($my_array); print_r($my_array); ?>

  22. Asort() Accepts an associative array and sorts its values preserving the keys <?php $my_array = array("b" => "Rabbit", "c" => "Dog", "a" => "Cat"); asort($my_array); print_r($my_array); ?>

  23. Ksort() - Sorts an associative array by keys <?php $my_array = array("b" => "Ruler", "c" => "Sharpener", "a" => "Book"); ksort($my_array); print_r($my_array); ?>

  24. Questions? • What is the index number of the last element of the array defined below? $users=array(“Harry”,”Bob”, “Sandy”); • What would be the easiest way to add “Susan” to the array defined above?

  25. Answer <?php $users=array("Harry","Bob", "Sandy"); foreach ($users as $item) { print ("$item<br>"); } $users[]="Sally"; foreach ($users as $item) { print ("$item<br>"); } ?>

  26. Lifecycle of an PHP Web Application 2. Specification of Requirements 3. Design 4. Programming 1. Requirements Analysis 5. Marketing 6. Analysis of Statistics and Maintenance

  27. Who is your targeted audience? • Knowing who they are will help you understand what they need, in terms of what kind of functionality should your website provide them with, that they will require? Will they need product reviews? Will they be searching for the lowest prices? Etc. • Based on this you can write all the functionalities of your website, all the requirements your website must fulfil • These requirements and the analysis of your target user will help you with the next steps Step 1. Website Requirements and Analysis

  28. Revisit requirements in step 1 and for each you will develop a use-case • A use-case is where you will determine 'what will the user do/ what action will the user take'. Here's an example of a use case:User Begins at Home Page --> User clicks on Featured Item Image --> User sees item description --> User goes to merchant site via Link • use-case scenarios - if the user doesn't find what they're looking for, perhaps we can offer an 'alternative' which is related to what they're looking for • Other requirements you need to consider are your own requirements of the website - what happens when the website grows and you no longer need only 5 merchants, you now need 50 • Once you have identified what you will need and what the user will need, you're ready plan the website structure and design Step 2 Specification of Requirements

  29. What PHP pages will be needed? • What Database tables and columns will be need to be created? • What information will the PHP pages need from the database? Step 3 - Design

  30. When you have decided upon any of the above project needs it is important that you document these decisions so that they are effectively communicated to other development team members • It is important that you dedicate enough time to your design phase • Defects created in the design phase will cause delays in later stages of the project life. Design

  31. Future Requirements • Additional functionality may be demanded of an PHP application after deployment • It is important that you design an application that is easily modified and therefore reduces the inefficient practice of recoding Overall • Creating a solid design before moving on to the programming phase ensures maintainability and readability. Design

  32. There are a number of good coding practices than are proposed to enhance the reliability,performance and ease of maintenance of PHP Applications • Documentation • Commenting • Commenting is especially lengthy when dealing with lengthy PHP scripts • With comments present a new developer can skim quickly through the source code, reading just the comments to get an understanding • Variables should always be logically named in order for developers to understand the function of the variable Step 4 Programming

  33. Documentation • A Naming convention should also be chosen for your variables • By having a prefix developers can quickly determine the type of information that you are storing in a variable • Using such a notation is useful in PHP, where all variables are declared using $ Programming

  34. Suggested Prefixes for Variable Names

  35. Preventative • Use an editor that highlights the matching pair of brackets () and {} when one or other is selected allowing you to see mismatched pairs • Put a comment after each closing brace to indicate which condition is closed • Reactive • Comment out the nested conditions until the code works as intended then uncomment pairs until you discover the problem • You can print out the code and score off matching pairs until you again discover the problem Debugging Tips PHP

  36. Modularization • A modularised program is one that is broken down into discrete modules • Each module serves a sole, unique purpose • Modular programming can be implemented in PHP through the use of user defined functions • Modularisation can also be implemented through Server Side Includes • Modularised code is: • Easy to Write • Easy to Debug • Easy to Understand. • Easy to change Modularisation Divide and Conquer

  37. Performance is key a feature - need to design for performance up front, or else you get to rewrite your application Improving Performance

  38. Use Local Variables in Functions • Local variables are those declared within functions • Within a function local variable access is faster than global variable access • Use of local variables also tends to make code cleaner Improving Performance

  39. Session Variables • Avoid overuse of session variables • Session variables can slow down the application • Alternatively use Cookie for maintaining state Improving Performance

  40. Problem 1: Using MySQL directly • One common problem is older PHP code using the mysql_ functions to access the database directly • Problem 2: Not using auto-increment functionality • most modern databases have the ability to create auto numbers on a per-record basis these should be utilised efficiently Database Issues

  41. Problem 3: Using multiple databases • Business requirements may dictate the need application in which each table is in a separate database but avoid if at all possible • Problem 4: Not using relations Continued..

  42. Problem 5: The n+1 pattern • Use one query to retrieve the list of all the entities and associated attributes Continued..

  43. The PHP parser requires that we use a semi-colon at the end of each PHP statement, otherwise it gets confused Dealing with PHP errors

  44. <html> <head><title>Debug Example</title></head> <body> <?php echo "<h2>Debugging Workshop</h2>" echo "<p>We are practicing how to fix various errors</p>"; ?> </body> </html> • PHP Parse error: parse error, unexpected T_ECHO, expecting ',' or ';' in c:\Inetpub\wwwroot\MBSEBUS\CHeavin\PHP\dealing errors.php on line 6 Dealing with PHP errors

  45. There has been a parse error: The PHP interpreter has come across an error and doesn't know what it is supposed to do, so just stops • It wasn't expecting another echo (T_ECHO) statement, as it hadn't finished the first one • If the next line after the missing semi-colon was an if statement or a while statement etc then these two would be unexpected (T_IF and T_WHILE etc) • What the interpreter was expecting was a ' , ' or a ' ; ' - which we know is what was missing Dealing with PHP errors

  46. Which file this was in i.e. Inetpub\wwwroot\MBSEBUS\CHeavin\PHP\dealing errors.php - useful if you have included functions from different files • Which line the PHP interpreter finds a semi-colon in - which is actually the next line - but does act as an indicator in the script as to where the problem lies Dealing with PHP errors

  47. How will people find it? • Is it well optimized for search engines? Use heading tags, bold tags, place your targeted keywords higher up, use alt tags, etc but do not at any time substitute the user-friendly design for a better SEO'd website. • Pay-per-click marketing • Try and find some forums which are related to the website you built, become an active user/poster. • Do not spam at any time. • Make some flyers, hand them out at busy places in your town/city etc. • This should all be in your business-plan you created before you even considered Step 1. Step 5 Marketing (SEO)

  48. You should have a functional website receiving some targeted traffic and converting well. • How well is it really converting? • How many click-throughs you've sent to each merchant • How well a merchant converts them? • How many visitors you received etc. ? • Maintenance • Disable existing merchants and give other merchants a better chance to see how they perform • Redesign webpages based on traffic Step 6 Analysis of Statistics and Maintenance

  49. http://websearch.about.com/library/quizzes/seo_quiz/blseoquiz.htmhttp://websearch.about.com/library/quizzes/seo_quiz/blseoquiz.htm

  50. Blacknight • http://www.blacknight.com/ • Minimus Hosting 4.95 per month • Databases • Mysql 4.1 • Mysql 5.0 • Ms SQL 2005 • Technology • Perl • PHP • .NET 2.0 / 3.5 • Disk space MB: 10GB • Monthly transfer GB: 100 GB

More Related