Professional LAMP Linux Apache, MySQL and PHP5 Web Development phần 8 ppsx

41 287 0
Professional LAMP Linux Apache, MySQL and PHP5 Web Development phần 8 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

<?php require_once ‘class.WebImage.php’; $img = new WebImage(); $img->load(‘base.png’); $img->caption(‘An example of plantlife found on Maui.’, ‘FUJIWIDR.TTF’, 15, 5, true); $img->display(); ?> If everything goes as planned, you should see something similar to Figure 10.4. Figure 10.4 261 PHP Extensions 13_59723x ch10.qxd 10/31/05 6:36 PM Page 261 Last, try out the image logo application. In this example, you’re going to place a logo in the lower-right corner of the image, on top of the caption box: <?php require_once ‘class.WebImage.php’; $img = new WebImage(); $img->load(‘base.png’); $img->caption(‘An example of plantlife found on Maui.’, ‘FUJIWIDR.TTF’, 13, 5, true); $img->logo(‘logo.png’, ‘r’, ‘b’, 5, 0.3); $img->display(); ?> And now, a logo should appear, resized a little, in the lower-right corner with 5px of padding, as in Figure 10.5. Figure 10.5 262 Chapter 10 13_59723x ch10.qxd 10/31/05 6:36 PM Page 262 As you can see, using the GD library is not hard to use and allows for quite a bit of flexibility and control over your images. There are many other more advanced functions you can use, all of which can be found at the GD section of the PHP Manual ( http://www.php.net/gd). Ming Ming is a third-party extension to PHP that allows a user to create Shockwave Flash files without actu- ally having to use Macromedia’s Flash studio. The functionality that Ming provides isn’t always the same as what is available in Macromedia’s Flash, because of the nature of how the Flash files are created using PHP and Ming. Ming does provide a method to create Flash files that is low cost and allows for content to be dynamically created when it is needed. About Ming The usefulness of dynamically created Flash files can sometimes be lost for some people, especially because you will not have the precise visual control over the content layout that people who use Macromedia’s Flash Studio employ. Also, the feature set of Ming is limited to that of Flash version 4, which is several ver- sions behind the latest available. But being able to script the creation and add dynamic content to the appli- cation is something that you can’t do using Macromedia’s Flash Studio. This can be helpful in distributing content to users where you need the features of Flash but also want to personalize the content for the user. Ming itself is actually a third-party extension that has had PHP wrapper extensions written for it, so it needs to be compiled into the PHP binary when the binary is built. Instructions for Ming installation with PHP can be found on PHP’s website ( http://www.php.net/ming). More information about Ming itself can be found at Ming’s site on SourceForge.Net ( http://ming.sourceforge.net). There are also many tutorials and examples available on the Internet that can help to illustrate the functionality of Ming as well as provide pieces of code that are suitable to be used as a foundation to build on for your Flash movies. Ming is implemented in PHP as objects, so that any time you create a shockwave file with Ming in PHP you need to at least instantiate an instance of the SWFmovie object. The following is some code of a very simple file generated with Ming and PHP. To run this code, insert it into a PHP file with no other content in it, and then view that file in a web browser that has the Flash plug-in installed: <?php header(‘Content-type: application/x-shockwave-flash’); $a= new SWFmovie(); $a->setDimension(100,100); //width and length in that order $a->setBackground(0,0,255); // red, green, and blue integers $a->output(); ?> This does not generate much, but it does produce a giant blue screen in your browser. Examining the code, you can see some of the necessary pieces that will need to be included in any Flash file created with Ming. The first line tells PHP to set the Content-type header so that the browser knows that it is a shockwave file and to load the appropriate plug-in for it. The next line actually creates the instance of the SWFMovie object. The next two lines are optional, but without them, it would be hard to tell that anything was generated, as they set the size of the shockwave file as well as make its background blue. The last line tells PHP to write the Ming generated file out to the browser. The only thing to really make 263 PHP Extensions 13_59723x ch10.qxd 10/31/05 6:36 PM Page 263 sure to do here is set the proper header Content-type before outputting the movie as well as make sure no other content is sent to the browser, such as stray lines and white space. There can only be one instance of the SWFMovie object, but you can include multiple mini movies in one SWFMovie object. In order to do this, you need to use another object, the SWFSprite object. This object has similar qualities and attributes to the SWFMovie object, but isn’t limited to only one per movie. The advan- tage to this is that you can have multiple animations showing at the same time in the same flash movie. Each of the animations can even be running at different rates as well as be different lengths in time. Flash files use frames, just like frames in a movie or animation. The objects SWFMovie and SWFSprite both have functions to add new frames to them. Frames are useful in that you can display different objects to the screen by including them in specific frames. This means that if you want two or more objects to be displayed at the same time, they need to have a common frame. Once an object is added to a frame, every frame after it contains that object until the object is removed from the movie. Also, just like a movie or animation you can go forwards or backwards, as well as skipping to a specific frame using the SWFAction object. This use of frames provides a better way to group objects as well as gener- ate timelines in your Flash movies. Ming and Flash both use a coordinate system that may be different than what you’re used to. The unit of distance that is used by Flash is the twip. The twip is defined as being exactly 1 ⁄1440 of an inch or 1 ⁄20 of a point in size. This measurement usually is simplified for easy conversion to a value of 20 twip units in 1 pixel. However, this can be an arbitrary value, as the Flash player will scale the movie to the size of the player window itself. Fortunately, the SWFBitmap object included in Ming has functionality to deter- mine what size an image is in twips. Therefore, if you need to have a movie with dimensions based on the size of an image, you simply need to create the SWFBitmap object, read its width and height values, and then set the dimensions of the movie itself based on it. The dimension of a movie does not necessar- ily need to be set until right before it is displayed. Objects in Ming There are a total of 13 objects that PHP provides to generate Flash files with Ming. You can use a combi- nation of these objects to create many complex Flash files with a wide variety of functionality. They are as follows: ❑ The SWFAction object lets you add logic and functionality beyond a simple image display to your Flash file. Using SWFAction you can move images and shapes around for things such as games, as well as read and set properties of objects in the Flash file. Also, you can include some ActionScript scripts, which is Flash’s version of JavaScript and is quite similar. This object is used commonly with the SWFButton object to perform some action when the user presses the button. Common actions used are the displaying of specific frames in a Flash movie based on a response from the user. ❑ The SWFBitmap object allows for images to be added to the Flash file. There are several limita- tions, though, as only non-progressive scan JPEG images and DBL (“define bits lossless”) images can be added this way. Any other image needs to be converted to one of these formats using either another extension, such as GD, or by making a system call to a utility. This objects many times is used with SWFSprite and the SWFShape objects. ❑ The SWFButton object adds a button to your Flash file. This button can be used to initiate an action of the SWFAction object. It reacts to common mouse actions such as mousedown, mouseup, and rollover. A shape can be added to the button to change its appearance. 264 Chapter 10 13_59723x ch10.qxd 10/31/05 6:36 PM Page 264 ❑ The SWFDisplayItem object allows a shape, text object, sprite, or button to be manipulated after being added to a movie by referencing the item using its returned handle after being added to the movie. Operations such as skewing, scaling, and moving items are all possible operations. ❑ The SWFFill object is generated by use of the addFill method of the SWFShape object. It allows the fill to be transformed by rotating, skewing, and scaling the fill of the shape. ❑ The SWFFont object loads a font for use by the SWFText object. The font can either be a font def- inition block (FDB) or a browser-defined font reference. ❑ The SWFGradient object creates a gradient that can then be used by the SWFShape method addFill(). ❑ The SWFMorph will take two shapes and morph the first into the second shape. This can be used for some basic animation. ❑ The SWFMovie object is the one object that is necessary for any other objects to work correctly, as it is the object that actually writes the Flash file out, either to a file or to a browser. ❑ The SWFShape object generates a shape. The shape is actually drawn by passing coordinates that are drawn with an imaginary pen. With the right coordinates, almost any shape can be gen- erated. Also, as mentioned before, this is used with the SWFBitmap object to add an image file to the movie. ❑ The SWFSprite object generates a “movie clip” or animation by adding frames to the object. A frame contains one of the other objects, such as SWFShape. There can be multiple SWFSprite objects in a single frame so that two animations are seen going at the same time. The advantage of adding images to a SWFSprite object compared to just a SWFMovie object is that it encapsu- lates the objects better for manipulation. ❑ The SWFText object displays text in a Flash animation. An alternative to using the SWFText object if you need to display only small amounts of static information is to just use images instead of using Flash to write the text. ❑ The SWFTextField is similar to a SWFText object, but with a few differences. SWFTextField objects can’t be rotated or skewed, but can function as form entries. Creating a Flash Display With a few more lines of code, you can expand the earlier example to something that is slightly more interesting to look at: <?php header(‘Content-type: application/x-shockwave-flash’); $a= new SWFMovie(); $a->setDimension(100,100); //width and length in that order $a->setBackground(0,0,255); // red, green, and blue integers $s =new SWFShape(); //generate a shape object $s->setLine(4, 30, 60, 100); //set the line width to 4 along // with red, green, and blue integer values $s->setLeftFill($s->addFill(300, 200, 100)); //set the color of the shape with red, green // and integer values $s->movePenTo(20, 20); 265 PHP Extensions 13_59723x ch10.qxd 10/31/05 6:36 PM Page 265 //move our imaginary pen to a new location $s->drawLineTo(20, 80); //draw lines to a new set of points $s->drawLineTo(80, 80); $s->drawlineTo(80,20); $s->drawLineTo(20,20); $a->add($s); //add the shape to the movie $a->nextFrame(); //advance a frame in the movie $a->output(); //output everything to the browser ?> The output generated from the movie is not anything special, but it demonstrates a few of the basic methods of some of the more important objects. The output should be a blue background with a green square in the middle of it. For a more in depth example to illustrate the functionality of Ming, you’re going to generate a slide show with it. You will be using images of all of the same size and shape to make things easier, and all images will be explicitly named. Create a new file and include the following lines of code: <?php //create a movie object $aMovie = new SWFMovie(); //set the background to white $aMovie->setBackground(255, 255, 255); After the initial setup, you need to add references to images to include in the slide show. Here, a simple array of image names is used, but this could be expanded to read straight from a directory or even a database. Also, in this example all images are assumed to have sizes of a height and width of 200 pixels. To make sizing the movie and expansion on the code easier, an instance of one image is made to read its width and height, even though all images in the example are supposed to be 200 × 200 pixels. Try it: //images to display $images = array(“1.jpg”, “2.jpg”, “3.jpg”); $bitmapImage = new SWFBitmap(fOpen($images[1], “rb”)); $w = $bitmapImage->getWidth(); $h = $bitmapImage->getHeight(); A SWFSprite is created that will act as a mini-movie in the slideshow, and will actually be what is con- trolled by the user. In order to prevent it from just showing all of the images a default action of stop() is added to it. Also the size of the movie is calculated from the size of the images with extra space given to allow for buttons to be added underneath the images. Here’s the code: //create a sprite which will act as a mini movie $sprite = new SWFSprite(); //add stop action to the first frame $sprite->add(new SWFAction(“stop();”)); //set the size of the movie with extra psce for buttons $aMovie->setDimension((1*$w),(1.5* $h)+3); 266 Chapter 10 13_59723x ch10.qxd 10/31/05 6:36 PM Page 266 Now each of the images needs to be added to the sprite, which can be easily achieved by iterating through the array. Each of the images are first converted to SWFBitmap objects, and then added as fills to SWFShape objects. After a line has been drawn around the shape, it is added to the SWFSprite object and the SWFSprite object goes to the next frame: //loop through all of the images for($i=0; $i<count($images);$i++){ //create a bitmap from an image $bitmapImage = new SWFBitmap(fopen($images[$i], “rb”)); //create a shape object to hold the image $shape = new SWFShape(); //generate the fill for the shape of the image $fill = $shape->addFill($bitmapImage); //add the fill to the shape $shape->setRightFill($fill); //draw a line around the shape to set the size $shape->drawLine($w, 0); $shape->drawLine(0, $h); $shape->drawLine(-$w, 0); $shape->drawLine(0, -$h); //add the shape to the sprite so that it is displayed $sprite->add($shape); //generate a new frame and go to it $sprite->nextFrame(); } Because the sprite will not return to the first frame automatically, there needs to be an action added to the last frame that takes it to the first frame. The gotoFrame() action accepts a frame number as an argument; here, frame 0 is used as it is the first frame in the sprite. Another frame is then added to the sprite in order to make sure everything is included in the SWFSprite object: //goto frame 0 $sprite->add(new SWFAction(“gotoFrame(0);”)); //again generate a new frame $sprite->nextFrame(); Now that the sprite has finished, it needs to be added to the SWFMovie object. As it is added to the movie, it will return a handler that can be used as a reference to the sprite so that it can be controlled. A name is assigned to it and using the handler, you move the sprite into position: //add the sprite and get its handler $handler = $aMovie->add($sprite); //we can name the sprite now with the handler $handler->setName(“images”); //we can move the sprite also with the handler $handler->moveTo(0,2); 267 PHP Extensions 13_59723x ch10.qxd 10/31/05 6:36 PM Page 267 In order to create a button to control the slide show, you create a new SWFShape object and add a button image to it //create a shape again $shape = new SWFShape(); //create another bitmap this time for a button image $bitmapImage = new SWFBitmap(fopen(“button.jpg”, “rb”)); $file = $shape->addFill($bitmapImage); $shape->setRightFill($fill); //create the border around the shape $shape->drawLine($w, 0); $shape->drawLine(0, $h); $shape->drawLine(-$w, 0); $shape->drawLine(0, -$h); A SWFButton object is instantiated and the button shape is added to the SWFButton object. The default flags are also set for the button, which allows the program to perform actions based on if the button is pushed or not and if the mouse is over the button. An action is also added to the button to move the sprite to the next frame. //now actually create a button object $button = new SWFButton(); //add the shape to the button with all of its default flags which are //all actually predefined integer values $button->addShape($shape, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER); //add an action to go to the next frame //on the sprite. The sprite is referenced by “/images” $button->addAction(new SWFAction(“setTarget(‘/images’); nextFrame();”),SWFBUTTON_MOUSEDOWN); The button is then added to the movie and the handler returned. The button is then moved to just under the images and a new frame is added to the movie. The necessary browser headers are then generated and the movie is outputted: //add the button to the move and save the returned handler $handler = $aMovie->add($button); //use the handler to move the button below the images $handler->moveTo(0,$h+3); $aMovie->nextFrame(); //send the appropriate header to the browser header(“Content-Type:application/x-shockwave-flash”); //output the movie to the browser $aMovie->output(); ?> There are a few things to remember when using Ming. The first is that when you output directly to a browser, the Content-Type header must be sent before the SWFMovie object’s method output() is called. This sends the proper HTTP headers so that the browser knows to load the Shockwave Flash plug-in. This leads to another error that may occur: outputting anything besides the Content-Type header, such as blank lines. The outputting of content other than the header and the movie itself will 268 Chapter 10 13_59723x ch10.qxd 10/31/05 6:36 PM Page 268 corrupt the file, causing the browser to incorrectly display the file. Also, it helps to have a general layout of what you want your final output to look like. To help with laying out a Flash movie created with Ming, you can use a graphics program that provides a coordinates system or just plain graph paper. SimpleXML XML is everywhere these days, so it only makes sense that there should be an easy way to retrieve and interpret those files. Thankfully, PHP offers us an XML interface to utilize XML data, in a simple and easy-to-use extension: SimpleXML. SimpleXML is installed by default, but if you’re not going to use it, it is recommended that you disable it in php.ini. It should be noted that SimpleXML also requires PHP5. As the name suggests, the extension’s purpose is to access XML documents on a very basic level. To illustrate the ease with which this can be implemented, create a fictitious XML file that contains informa- tion on beachfront rentals (this file will be used in all of the examples): <?xml version=”1.0”?> <rentals> <description> <name>The Bayfront</name> <type>condo</type> <view>oceanfront</view> <space>1200 square feet</space> <location>Wrightsville Beach</location> <price>1000 per week</price> <bed_bath>3 bedrooms, 2 bathrooms</bed_bath> </description> <description> <name>Paradise</name> <type>house</type> <view>oceanfront</view> <space>1000 square feet</space> <location>Wrightsville Beach</location> <price>900 per week</price> <bed_bath>2 bedrooms, 2 bathrooms</bed_bath> </description> </rentals>> Now that you have the XML file, grab the information and put it into an object (using the simplexml_ load_file() function) so you can manipulate it: <?php if (file_exists(‘beachfront.xml’)) { $data = simplexml_load_file(‘beachfront.xml’); print_r($data); } ?> You can iterate through the object and display the results nicely (or at least in a more readable format). Add the following changes to simple.php: 269 PHP Extensions 13_59723x ch10.qxd 10/31/05 6:36 PM Page 269 <?php if (file_exists(‘beachfront.xml’)) { $data = simplexml_load_file(‘beachfront.xml’); foreach($data as $main) { echo “<hr>”; foreach ($main as $k => $v) { echo $k . “: “ . $v . “<br \>”; } } } ?> Besides simplexml_load_file(), there are a host of other functions that go along with the SimpleXML extension. simplexml_load_string() loads an XML document as a string. You must first assign its con- tents to a variable; then you may use the simplexml_load_string() function to parse the variable’s contents into the object for your use. If you would like to manipulate your object and then display the contents back out to the browser in the form of an XML file, you can use the $objectname->asXML() function. The attributes() and children() functions are helpful if you need to see the element’s attributes or the children of any of the object’s nodes. The simplexml_import_dom() function is helpful if you want to take a DOM node from a DOM document and turn it into a SimpleXMLElement.object. The xpath() function allows you to search through the XML document for a specific string. It uses the W3C’s Xpath to evaluate each node in your XML document, and is called “XPath” because the search keywords resemble the path to a file, as each element is similarly nested. If you would like to read more about XPath, visit the W3C’s documentation on the subject at http://www.w3.org/TR/xpath. This is sufficient if you want to perform the very simplest of queries, as in the following example: <?php if (file_exists(‘beachfront.xml’)) { $data = simplexml_load_file(‘beachfront.xml’); //find and list all the “locations” in our XML file //”locations” are under “descriptions” which are under “rentals” $find = $data->xpath(‘/rentals/description/location’); while (list(, $v) = each($find)) { echo $v. “\n”; } } ?> This script will give you all the values for the node named “location” within your XML file. If you want to take your query any further, you will have to use another method. Remember this is SimpleXML, not ComplexXML. SimpleXML offers a very quick and straightforward way to access a simple XML document. It does not allow for much flexibility, and it only works on the simplest of XML files. You will run into problems trying to run these functions on an XML file that contains HTML code within its content, for example. Otherwise, this is a lot easier to work with than many other XML/PHP interfaces available. 270 Chapter 10 13_59723x ch10.qxd 10/31/05 6:36 PM Page 270 [...]... differences in instantiation of the XMLHTTP and XMLHttpRequest interfaces and returns whichever version is available As previously described, the receipt of the response to an XMLHTTP request is handled with the firing of events and the triggering of appropriate event handlers The next set of code offers the typical way of handling the ReadyStateChange event firing and acting on only the event in which you... solutions, as it comes with a handy configuration and setup wizard 294 Caching Engines First, download the package appropriate for your system from http://zend.com/store/products/ zend-optimizer.php Then, decompress the archive, and go into the newly created directory: tar -xvzf ZendOptimizer-2.5.10a -linux- glibc21-i 386 .tar.gz cd ZendOptimizer-2.5.10a -linux- glibc21-i 386 As root, run the install wizard:... compression and increase transferred size Table continued on following page 293 Chapter 12 Directive Default eaccelerator.sessions eaccelerator.content Set In Description php.ini and httpd.conf You can tell eAccelerator where you want it to store session data and content with this directive A value of shm _and_ disk tells the caching engine to store session data and content in both shared memory and disk... allows for the creation of fat-client web applications, where the responsibility for a relatively large portion of the application processing is given to the client Specifically, AJAX applications often use XHTML and CSS for semantic markup and presentation, XML to format data that will be exchanged between client and server, and JavaScript to communicate with the server and manipulate the Document Object... drawback Still, SAJAX offers a method of simplifying the server-side handling AJAX requests from the client and the client-side handling of instantiating XMLHTTP request objects and issuing necessary requests CPAINT CPAINT (http://cpaint.sourceforge.net/) is the Cross-Platform Asynchronous Interface Toolkit It supports both plaint-text and XML response types Additionally, it has some support for retrieving... functionality, but they do not come close to the abstraction offered by JPSPAN Documentation and example code for JPSPAN are abundant and clear Both are in wiki format and are thus ever-growing The code itself is clean and easy to read, just like the XML it generates Furthermore, initial work is currently under development to embed JPSPAN in PHP frameworks to make it even easier to develop fat-client... traditional web application is understandable However, many traditional web applications would be harmed by the use of AJAX The commonality among applications that naturally tend to benefit from AJAX is that they are traditionally desktop applications GMail is a web- based version of an email client, which has previously performed best as a desktop application (indeed, the only real reason traditional web applications... use it 285 Caching Engines You’ve done your best to clean up your code and reduce processing load in your PHP scripts, but you just can’t seem to make your pages fast enough to keep your users happy Time to throw in the towel? Not quite — there’s more performance you can get out of your LAMP setup, and caching engines will help you do this When dealing with different caching solutions for PHP5, you... free as part of the PECL/PEAR repository APC originated with Daniel Cowgill and George Schlossnagle, and was released by Community Connect, Inc After the release of PHP5, Yahoo! modified APC to support the new Zend Engine, and it has since become part of PECL APC works by taking the compiled code from the PHP runtime engine and storing it in shared memory for later access Each time a script is downloaded,... eaccelerator.cache_dir /tmp/ eaccelerator php.ini and httpd.conf Specifies the directory to use for the disk cache, if eAccelerator is configured to use on-disk caching eaccelerator.enable 1 (enabled) php.ini, httpd.conf, htaccess, and user scripts Allows enabling and disabling of eAccelerator using the numeric values 1 and 0, correspondingly This setting is changeable in user scripts and htaccess files, so you can use . and get its handler $handler = $aMovie->add($sprite); //we can name the sprite now with the handler $handler->setName(“images”); //we can move the sprite also with the handler $handler->moveTo(0,2); 267 PHP. outputted: //add the button to the move and save the returned handler $handler = $aMovie->add($button); //use the handler to move the button below the images $handler->moveTo(0,$h+3); $aMovie->nextFrame(); //send. ( http://www.rfc-editor.org/rfc/rfc2616.txt) 2 78 Chapter 11 14_59723x ch11.qxd 10/31/05 6: 38 PM Page 2 78 With the exception of responseText and responseXML, these properties are mainly involved in determin- ing if and when a response

Ngày đăng: 12/08/2014, 23:23

Tài liệu cùng người dùng

Tài liệu liên quan