Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1802 Articles
article-image-managing-image-content-joomla
Packt
23 Feb 2010
3 min read
Save for later

Managing Image Content in Joomla!

Packt
23 Feb 2010
3 min read
Creating image galleries and slideshows Joomla! is a Content Management System designed primarily for organizing and managing website content. It contains numerous multimedia features built into it, but its main focus is providing two roles: Powerful CMS features, and a well-designed framework which allows additional features to be added to the system, thus creating powerful functionality. These additional features are called Extensions and are designed to plug in to the core Joomla! Framework and extend the functionality of it. With regards to the core Joomla! CMS, we have already looked at how images can be included into content items and modules. However, image galleries and slideshows are asking a bit more than just simple image management, and so require the power of extensions to provide these features: The number of multimedia extensions now available for Joomla! is staggering. We have extensions which can create complex galleries, stream in videos, and compile jukebox type audio features. Having considered at great length the best approach has resulted in one option. That is to highlight some of the most popular and useful image gallery and slideshow extensions, and hope that these will provide understanding as to the complex image management capability that can be achieved by using Joomla! Extensions. Image management extensions, and how to install them Before proceeding with covering third-party extension functionality, let's quickly cover how image extensions are added to your Joomla! site. As with most things in Joomla!, the process of installing extensions has had careful consideration from the development team, and is a very easy to perform. Most Joomla! Extensions come with their own installation instructions, and these general guidelines will help you get them installed on your site. Before installing anything, make sure you copy your file set and backup your site database. For the purpose of this example, I am going to install one of my favorite Joomla! Multimedia Extensions—the RokBox extension by RocketTheme. RokBox is a MooTools powered slideshow plugin that enables you to display numerous media formats with a professional pop-up screen lightbox effect: The installation steps are as follows: Download the required extension and save this download on your computer. The file will be in a .zip format, or possibly a .gzip or .tgz format which may require unzipping before installation: Log into your Joomla! Administrator's Control Panel, and navigate to the Extensions menu, then to Extension Manager. The page will default to the Install screen: Browse your computer for the extension .zip file using the Choose File button on this page and once the file is located, use the Upload File & Install button. The Joomla! Installation Manager will perform all of the work and if your extension has been built correctly, the installer will place all files and documents into their correct directories: An installation success message will show to inform you that the extension has been successfully installed. Some extensions success text may contain additional links to configuration pages for the extension.
Read more
  • 0
  • 0
  • 6073

article-image-adding-image-content-joomla
Packt
23 Feb 2010
6 min read
Save for later

Adding Image Content in Joomla!

Packt
23 Feb 2010
6 min read
Images and why we use them in websites Research suggests that images enhance learning by illustrating the concepts visually and by providing visual memory cues to the viewer. We have been using images to describe, tell stories, and record history since our human evolution. I have been in a few situations where, if a language barrier between me and the other party exists, we have resorted to a pencil and napkin in order to communicate effectively. Pictures can convey a message, which might take many thousands of words to describe. This non-textual communication and the visual emotions that the use of images can generate mean they are the perfect medium to complement or replace the text in our web pages: The previous image could easily take a thousand words to describe, which would look uninteresting to the reader and take up valuable space on our web pages. Instead the picture only utilizes a fraction of the space that our description would use and tells a story in itself. Not only do images describe a story, a moment in time, or a fantasy situation; they can provide a visual stimulus, which portrays a style or theme and sets a mood for the viewer. Many Joomla! Templates now contain a high percentage of graphical images in order to produce interesting designs and effects, such as this commercial example from http://www.yootheme.com: Many templates now utilize rounded edges for the graphics, or faded effects, and some create a 3D type effect on our two-dimensional computer screens. This is achieved by using shading and image layering effects. Others use images to create interesting navigation effects which could not be achieved without using these. Besides the design, navigation, and branding effects that images help provide, inside our content and modules, we use images to advertise and communicate to our site visitors. One important trick as web developers is to make sure our images are as optimized as they can be before asking our viewers to load them into their web browsers. This ensures a pleasant user experience because if a site is slow to load, or images are missing, these can be a big turn-off to your site visitors. Image formats and which ones to use Images can often make up 50 percent of a Joomla! website; sometimes even more. These images that get loaded into the browser can be part of your template design, or site images we have loaded into our modules and articles. Choosing an appropriate format for this image content will help optimize the loading times of your web pages, which is one of the most important considerations when building a multimedia rich website: There are a few simple rules we can use in order to choose an appropriate image format. The most important criterion for the final file is the size. The previous image is exported using Adobe Fireworks on a Mac computer. External image editors such as the GNU Image Manipulation Program (GIMP) are good open source solutions for manipulating and optimizing images for the web. GIMP can be downloaded by visiting http://www.gimp.org. With each image requiring loading by the user's browser, page-loading times can be easily affected with the quality and quantity of images you use in your web pages. This in turn results in end user frustration (especially on dial-up Internet connections) and loss of site traffic. Digital images Before we proceed further into file sizes and file types, it is important to mention a note about digital images. Because all of our web page images are stored or viewed on a computer device, they are in a digital format (an electronic file stored using zeros and ones). A digital image is built up of tiny elements called pixels. Pixels are the building blocks of all digital images and are small adjoining squares in a matrix across the length and width of your image. Pixels are so small that you cannot easily see them when the image is viewed on your computer screen: Each pixel is an element containing a single solid color, and when put together all of these tiny dots make up your final image. Usually, more pixels per area make up a higher quality image, but there is a poin t when viewed with the human eye on electronic devices that you cannot actually see the extra detail that the additional pixel's bring to the image: The physical dimensions of a digital image are measured in pixels and all digital images have what is called an image resolution (the image height and width dimensions in pixels). It is possible to save your digital images in numerous formats and compressions in order to optimize the file quality and size. Image editing programs, such as Adobe Fireworks, are specifically designed with web optimization and export options: Lossy and lossless data compression Data compression is an important part of our digital world. File compression is useful because it helps in reducing the consumption of expensive resources such as transmission bandwidth and computer hard disk space. Almost all digital images that we use on the web have been resized or compressed to some degree. When editing or saving files in popular software editing programs, many options are provided to help optimize digital images. Lossy and lossless compression are two terms that describe the compression type of a file, and whether or not the file retains all of the original data once compression and then decompression of that file has taken place. The preferred formats for digital web images (such as JPEG and GIF) all fall into one of the following compression types: LossyA lossy data compression is one where the compression attempts to eliminate redundant or unnecessary file information. Generally, once a file has been compressed, the information that was lost during compression cannot be recovered again. Hence, it is a degradable compression type, and as the file is compressed and decompressed each time, the quality of the file will suffer from generation loss.JPEG and MP3 files are good examples of formats that use lossy compression. LosslessLossless file compression makes use of data compression that retains every single bit of data that was in the original file before compression.Lossless compression is often used when an identical representation of the original data is required once a file has been compressed and then decompressed again. As an example, it is used for the popular ZIP file format. Image formats such as PNG and GIF fall into the lossless compression type. For now, it is not so important to go into any more detail on these compression types, but the following image formats fall into both of these compression categories. It is possible to optimize your website images by choosing the correct format to save and present them to your site users.
Read more
  • 0
  • 0
  • 3389

article-image-installing-php-nuke
Packt
22 Feb 2010
10 min read
Save for later

Installing PHP-Nuke

Packt
22 Feb 2010
10 min read
The steps to install and configure PHP-Nuke are simple: Download and extract the PHP-Nuke files. Download and apply ChatServ's patches. Create the database for PHP-Nuke. Create a database user, and fill the database with data. Make some simple changes to the PHP-Nuke configuration file. Copy the PHP-Nuke files to the document root of the web server. Test it out! Let's get started. Downloading PHP-Nuke The latest version of PHP-Nuke can be downloaded at phpnuke.org downloads page: http://www.phpnuke.org/modules.php?name=Downloads&d_op=viewdownload&cid=1 You can also obtain older versions of PHP-Nuke, including version 1.0, from SourceForge: http://sourceforge.net/project/showfiles.php?group_id=7511&package_id=7622 SourceForge is the world's largest home of open-source projects. Many projects use SourceForge's facilities to host and maintain their projects. You can find almost anything you want on SourceForge—whether it is in a usable state or has been updated recently is another matter. Extracting PHP-Nuke Once you have downloaded PHP-Nuke, you should extract the contents of the PHP-Nuke ZIP archive to the root of your c: drive. You will have to create a folder called PHP-Nuke-7.8 in the root of your c: drive. (If you extract the files elsewhere, create the folder PHP-Nuke-7.8 and copy the contents of the main unzipped folder to this new folder). If you don't have a tool for extracting the files, you can download an evaluation edition (or buy a full edition) of WinZip from www.winzip.com. There are also free, powerful, extracting tools such as ZipGenius (http://www.zipgenius.it/index_eng.htm) and 7-Zip (http://sourceforge.net/projects/sevenzip/) among others. In the PHP-Nuke-7.8 folder, you will find three subfolders called html, sql, and upgrades. The upgrades folder contains scripts that handle upgrading the database between different versions, the sql folder contains the definition of the PHP-Nuke database that we will be working with, and the html folder contains the guts of your PHP-Nuke installation. The html folder contains all the PHP scripts, HTML files, images, CSS stylesheets, and so on that drive PHP-Nuke. Within the html folder are further subfolders; some of these include: modules: Contains the modules that make up your PHP-Nuke site. Modules are the essence of PHP-Nuke's operation; we look at them from article Your First Page onwards. blocks: Contains PHP-Nuke's blocks. Blocks are 'mini-functionality' units and usually provide snippet views of modules. We will look at blocks in article Managing the Site. language: Contains PHP-Nuke language files. These allow the language of PHP-Nuke's interface to be changed. images: Contains images used in the display of the PHP-Nuke site. themes: Contains the themes for PHP-Nuke. The use of themes allows you to completely change the look of a PHP-Nuke site with a click of a button. includes, db: Contain code to support the running of PHP-Nuke. The db folder, for example, contains database access code. admin: Contains code to power the administration area of your site. Downloading the Patches No software is without its flaws, and PHP-Nuke is no exception. After a release, the large user community invariably finds problems and potential security holes. Furthermore, PHP-Nuke also contains features such as its forum, which is in fact the phpBB application specially modified to work with PHP-Nuke. phpBB itself is updated on a regular basis to correct critical security vulnerabilities or to fix other problems, and consequently the corresponding part of PHP-Nuke also needs to be updated. Rather than releasing a new version of PHP-Nuke for these situations, patches for its various parts are released. ChatServ's patches from www.nukeresources.com are mostly concerned with variable validation, in other words, making sure that the variables used in the application are of the right type for storing in the database. This has been an area of weakness with many earlier versions of PHP-Nuke. The patches are often incorporated into subsequent versions of PHP-Nuke so that each new version becomes more robust. Note that you don't have to apply the patches, and PHP-Nuke will still work without them. However, by applying them you will have taken a good step towards improving the security of your site. If you navigate to http://www.nukeresources.com, there is a handy menu on the front page to access the patches: To obtain the patch corresponding to your version, click the link and you will be taken to the relevant file (of course, www.nukeresources is a PHP-Nuke powered site!). Click on the Nuke 7.8 link to go to the Downloads page of www.nukeresources.com. On this page, clicking the Download this file Now! link will download the patches for PHP-Nuke 7.8. The name of this file will be of the form 78patched.tar.gz. This is a GZIP compressed file that contains all the patches that we are about to apply. The GZIP file can be extracted with WinZip, or any of the other utilities we discussed earlier. The patches are simply modified versions of the original PHP-Nuke files. The original files have been modified to address various security issues that may have been identified since the initial release, or maybe since the last version of the patch. Applying the Patches To apply the patches, first we need to extract the 78patched.tar.gz file. We will extract the files into a folder called patches that we will create in the PHP-Nuke-7.8 folder. After extracting the files, copy the contents of the patches folder to your html folder. Do not copy the patches folder, copy its contents. The patches folder contains files that replace the files in the default installation, and you get a Confirm File Replace window. Select Yes for all the files, and when the copying is complete, your installation is ready to go. We have performed this patching immediately after installing PHP-Nuke, but we could have done this at any time. Doing it at this point is more sensible as it means that we are working on the most secure version of PHP-Nuke. Also, the patch process we have described here overwrites existing PHP-Nuke installation files. If you have modified these files, then the changes will be lost on applying the patch. Thus applying the patches later without disturbing any of your changes becomes more demanding. There is one further thing to watch for after applying the patches. You may find that the patched files have had their permissions set to read-only, and that you are unable to modify the files. To modify the files (and we do have to modify at least the config.php file in this article) you will need to remove this setting. You can do this on Windows by right-clicking on the file, selecting Properties from the menu, unchecking the Read-only setting, and clicking the OK button: We've done almost all the work with the files that we need to; now we turn our attention to creating and populating PHP-Nuke's database. Preparing the PHP-Nuke Database We'll be using the phpMyAdmin tool to do our database work. phpMyAdmin is part of the XAMPP installation (detailed in Appendix A), or can be downloaded from www.phpmyadmin.net, if you don't already have it. phpMyAdmin provides a powerful web interface for working with your MySQL databases. First of all, open your browser and navigate to http://localhost/phpmyadmin/, or whatever the location of your phpMyAdmin installation is: Creating the Database We need to create an empty database for PHP-Nuke to hold all the data about our site. To do this, we simply enter a name for our database into the Create new database textbox: We will call our database nuke. Enter this, and click the Create button. The name you give doesn't particularly matter, as long as it is not the name of some already existing database. If you try to use the same name as an already existing database, phpMyAdmin will inform you of this, and no action will be taken. The exact name isn't particularly important at this point because there is another configuration step coming up, which requires us to tell PHP-Nuke the name of the database we've created for it. After clicking Create, the screen will reload and you will be notified of the successful creation of your database: Creating a Database User Before we start populating the database, we will create a database user that can access only the PHP-Nuke database. This user is not a human, but will be used by PHP-Nuke to connect to the database while it performs its data-handling activities. The advantage of creating a database user is that it adds an extra level of security to our installation. PHP-Nuke will be able to work with data only in this database of the MySQL server, and no other. Also, PHP-Nuke will be restricted in the operations it can perform on the tables in the database. We will need to create a username for this boxed-in user to access the nuke database. Let's call our user nuker and go with the password nukepassword. However, in order to add an extra level of security we will introduce some digits into nukepassword, and some other slight twists, to strengthen it, and so use the word No0kPassv0rd as our database user password. To create the database user, click the SQL tab, and enter the following into the Run SQL query/queries on database textbox: GRANT ALL PRIVILEGES ON nuke.* TO nuker@localhost IDENTIFIED BY 'No0kPassv0rd' WITH GRANT OPTION Your screen should look like this: Click the Go button, and the database user will be created: Populating the Database Now we are ready to fill our database with data for PHP-Nuke. This doesn't mean we start typing the data in ourselves; the data comes with the PHP-Nuke installation. This data is found in a file called nuke.sql in the sql folder of the PHP-Nuke installation. This file contains a number of SQL statements that define the tables within the database and also fill them with 'raw' data for the site. However, before we fill the database with the tables from this file, we need to make a modification to this file. By default, the name of each database table in PHP-Nuke begins with nuke_. For example, there is a table with the name nuke_stories that holds information about stories, and a table called nuke_topics that holds information about story topics. These are just two of the tables; there are more than 90 in the standard installation. The word nuke_ is a 'table prefix', and is used to ensure that there are no clashes between the names of PHP-Nuke's tables and tables from another application in the same database, since the rest of the table name is descriptive of the data stored in the table, and other applications may have similarly named tables. What this does mean is that unless this table prefix is changed, the table names in your PHP-Nuke database will be known to anyone attempting to hack your site. Many of the typical attacks used to damage PHP-Nuke are based around the fact that the names of the tables in the database powering a PHP-Nuke site are known. By changing the table prefix to something less obvious, you have taken another step to making your site more secure.
Read more
  • 0
  • 8
  • 41236

article-image-introduction-php-nuke
Packt
22 Feb 2010
6 min read
Save for later

An Introduction to PHP-Nuke

Packt
22 Feb 2010
6 min read
This is the first article of the series in which we will cover the introduction to PHP-Nuke. PHP-Nuke is a free tool to manage the content of dynamic websites. To be more specific, PHP-Nuke is an open-source content management system. In fact, you could say it is 'the' open-source content management system. Since it is vastly popular, a number of other similar systems have sprung from it, and even similar systems based around very different technologies that owe nothing to it in terms of code have added 'Nuke' to their name as homage. Although the first paragraph conveys something of the history and grandeur of PHP-Nuke, it doesn't answer the basic question of what it can actually do for you. PHP-Nuke allows you to create a dynamic, community-driven website with minimum effort and programming knowledge. To get the most out of PHP-Nuke, a knowledge of web development will prove to be useful, but even then, PHP-Nuke is written in the PHP scripting language (as can be deduced from the name), which is probably the most popular and straightforward language for creating websites and web applications. The first PHP-Nuke release in June 2000 was created by a developer named Francisco Burzi to power his site, Linux Preview. Since then, PHP-Nuke has evolved under his guidance to the system it is today. PHP-Nuke is truly one of the Internet's legendary applications. In this article, we will take our first look at PHP-Nuke, understand what it can do, find out where to go for further resources, and briefly discuss the site we will create in this article series. What PHP-Nuke Can Do for You PHP-Nuke is ideal for creating community-driven websites. The 'community' part of 'community-driven' means that the site is geared towards a particular group of people with similar interests. Maybe this community is concerned with wine making, flowers, programming, zombie films, or even dinosaurs. Maybe the community is actually a group of customers of a particular product. Of course, we are talking about an online community here. Whatever the community is into, the site can be structured to hold information relevant to the members; maybe it will be news stories about a forthcoming zombie film, links to other zombie sites, reviews, or synopses of other zombie films. The 'driven' part of 'community-driven' suggests that the information available on this site can be extended or enhanced by the members of the community. Members of the community may be able to shape what is on the site by posting comments, contributing or rating stories, and participating in discussions. After all, communities are made up of people, and people have views and opinions, and often like to express them! This is exactly what PHP-Nuke enables. More than being just a website, a PHP-Nuke site provides a rich and interactive environment for its visitors. The best bit is, you don't have to be an expert programmer to achieve all this. With only rudimentary knowledge of HTML, you can engineer a unique-looking PHP-Nuke website. The Visitor Experience The standard installation of PHP-Nuke provides many features for its visitors. Some of them are: Searchable news articles, organized into topics Ability of visitors to create an account on the site, and log in to their own personal area Ability of visitors to rate articles, and create discussions about them Straw polls and surveys Ability of visitors to submit their own stories to be published on the site An encyclopedia, in other words, a collection of entries organized alphabetically A catalog of web links or downloadable files Discussion forums Ability of visitors to select their own look for the site from a list of different 'themes' RSS syndication of your articles to share your content with other sites This is not a complete list either. And these are only some of the features that come with the standard installation. PHP-Nuke is a modular system; it can be customized and extended, and there is a huge range of third-party customizations and extensions to be found on the Internet. Any of these can add to the range of features your site provides. The Management Experience As a potential 'manager' of a PHP-Nuke site, as you read through the list of features above you may think they sound rather attractive, but you might also wonder how you will handle all of that. PHP-Nuke provides a web-based management interface. You, as the manager of the site, visit the site and log in with a special super user, or site administrator, account. After this, from the comfort of your web browser, you run the show: You can add new information, and edit, delete, or move existing pieces of information. You can approve articles submitted by the user to be shown on the site. You can decide the features of the site. You can control what is displayed on the pages. You can control who is able to see what. What Exactly is PHP-Nuke? PHP-Nuke is a collection of PHP scripts that run on a web server, connect to a database, and display the retrieved data in a systematic way. In other words, PHP-Nuke is a data-driven PHP web application. PHP-Nuke can be downloaded for free, and then installed to your local machine for testing and development. The files and the database can be uploaded to a web hosting service, so that your site will be available to anyone on the Internet. There are even web hosting services that offer PHP-Nuke installation at the click of a button. Modular Structure PHP-Nuke is built around a 'core' set of functions, which perform mundane tasks such as selecting what part of the application the user should be shown, checking who the user is, and what they can do on the site. The thing that makes PHP-Nuke exciting to the world is the set of modules that comes with it. These modules provide the real functionality of the site, and include ones for news and article management, downloads, and forums, among others. The modules can be switched on and off with ease, and other modules can be added to the system. There is no shortage of third-party modules on the Internet, and you can find a PHP-Nuke module for almost any imaginable purpose. Themed Interface The look of a PHP-Nuke site is controlled by a theme. This is a collection of images, colors, and other resources, and instructions that determine the layout of the page. A new theme can be selected, and your site will be transformed immediately. Visitors with a user account on the site are able to select their own personal theme. Multi-Lingual Interface PHP-Nuke comes with many language files. These contain translations of standard elements on the site interface. The availability of these translations reflects the international nature of the PHP-Nuke community. PHP-Nuke as an Open-Source Content Management System We used the expression 'open-source content management system' earlier in the article to describe PHP-Nuke. Let's take a closer a look at this term.
Read more
  • 0
  • 24
  • 14122

article-image-ajax-and-connection-manager-yahoo-user-interface-yui
Packt
22 Feb 2010
9 min read
Save for later

AJAX and Connection Manager with Yahoo User Interface (YUI)

Packt
22 Feb 2010
9 min read
As far as web interface design techniques are concerned, AJAX is definitely the way to go. The term AJAX has been part of the mainstream development community's vocabulary since early 2005, yet AJAX reinvented existing technologies as something new and exciting, and paved the way to a better, more attractive, and interactive web (sometimes referred to loosely as web 2.0) where web applications feel much more like desktop applications. The very first JavaScript libraries sprang into existence as a means of abstracting away the differences in AJAX implementation between platforms, thereby allowing developers to focus on the important things in web design instead of worrying about compatibility issues. The result in many cases is a quick and easy way for developers to cut down on the amount of code they are required to produce, and a better more interactive experience for end users and website visitors. The Connection Manager—A Special Introduction The Connection Manager utility is by no means the smallest, most light-weight component included with the YUI, but it's certainly not the largest either, yet it packs so much functionality into just 12Kb (for the –min version). Connection Manager provides a fast and reliable means of accessing server-side resources, such as PHP or ASP scripts and handling the response. A series of supporting objects manage the different stages of any asynchronous transactions, whilst providing additional functionality where necessary. Connection is one of just a few of the utilities that are supported by a single class; this makes looking up its methods nice and straight-forward. It also doesn't have any properties at all (although the objects that it creates all have their own members which hold various pieces of information), which makes using it even easier! This utility is what is known as a singleton utility, which means that there can only be one live instance of the utility at any one time, differing from many of the other components of the library. Don't worry though, this doesn't restrict you to only making one request; Connection will manage as many separate requests as you need. Because this utility is a singleton, there are important considerations that advanced coders may want to take note of. Unlike some of the other library components, Connection cannot be subclassed—all of its class's members are static, meaning that they won't be picked up when using the YAHOO global .extend() method. It wraps up the cross-browser creation of the XMLHttpRequest (XHR) object, as well as a simple to use object-based method of accessing the server response and any associated data, into a simple package which handles the request from start to finish. This requires minimal input from you, the developer, saving time as well as effort. Another object created by Connection is the response object, which is created once the transaction has completed. The response object gives you access via its members to a rich set of data including the id of the transaction, the HTTP status code and status message, and either the responseText and responseXML members depending on the format of the data returned. Like most of the other library components, Connection Manager provides a series of global custom events that can be used to hook into key moments during any transaction. We'll look at these events in more detail later on in the article but rest assured, there are events marking the start and completion of transactions, as well as success, failure, and abort events. The Connection utility has been a part of the YUI since its second public release (the 0.9.0 release) and has seen considerable bug fixing and refinement since this time. This makes it one of the more reliable and better documented utilities available. Connection is such a useful utility that it's used by several other library components in order to obtain data from remote sources. Other components that make use of Connection Manager include the AutoComplete control, DataTable, DataSource, and Tabview. It is one of the only library components not dependant on the DOM utility. All it requires are the YAHOO global utility and the Event utility. That doesn't mean that you can't include a reference to the DOM utility, however, to make use of its excellent DOM manipulation convenience methods. The XMLHttpRequest Object Interface When working with the Connection utility you'll never be required to manually create or access an XHR object directly. Instead, you talk to the utility and this works with the object for you using whichever code is appropriate for the browser in use. This means that you don't need separate methods of creating an XHR object in order to keep each browser happy. A transaction describes the complete process of making a request to the server and receiving and processing the response. Connection Manager handles transactions from beginning to end, providing different services at different points during a request. Transactions are initiated using the .asyncRequest() method which acts as a constructor for the connection object. The method takes several arguments: the first specifies the HTTP method that the transaction should use, the second specifies the URL of your server-side script while the third allows you to add a reference to a callback object. A fourth, optional, argument can also be used to specify a POST message if the HTTP method is set to use POST giving you an easy means of sending data to the server as well as retrieving it. This is rarely required however, even when using the POST method, as we shall see later in the article. It's also very easy to build in query string parameters if these are required to obtain the data that you are making the request for. It can be hard coded into a variable and then passed in as the second argument of the Connection constructor instead of setting the second argument manually within the constructor. Connection Manager takes these arguments and uses them to set up the XHR object that will be used for the transaction on your behalf. Once this has been done, and Connection has made the request, you then need to define a new object yourself that will allow you to react to a range of responses from the server. A Closer Look at the Response Object I briefly mentioned the response object that is created by the utility automatically once a transaction has completed, let's now take a slightly more in-depth view at this object. It will be created after any transaction, whether or not it was considered a success. The callback functions you define to handle successful or failed transactions (which we'll examine in more detail very shortly) are automatically passed to the response object as an argument. Accessing it is extremely easy and requires no additional intervention from yourself. If the transaction fails, this object gives you access to the HTTP failure code and HTTP status message which are received from the server. Examining these two members of the response object can highlight what happened to make the request fail, making it integral to any Connection implementation. If the transaction was a success, these two members will still be populated but with a success code and status message, and additional members such as responseText or responseXML will also contain data for you to manipulate. If you need to obtain the HTTP response headers sent by the server as part of the response, these can be obtained using either the getResponseHeader collection, or the getAllResponseHeaders member. In the case of file uploads, some of these members will not be available via the response object. File uploads are the one type of transaction that do not make use of the XHR object at all, so the HTTP code and status message members cannot be used. Similarly, there will not be either a textual or XML-based response when uploading files. Managing the Response with a Callback Object In order to successfully negotiate the response from the server, a literal callback object should be defined which allows you to deal quickly and easily with the information returned whether it is a success, failure, or another category of response. Each member of this object invokes a callback function or performs some other action relevant to your implementation. These members can be one of several types including another object, a function call or even a string or integer depending on the requirements of your application. The most common members you would use in your callback object would usually be based upon success and failure function calls to handle these basic response types, with each member calling its associated function when a particular HTTP response code is received by the response object. It's also very easy to add an additional member to this object which allows you to include data which may be useful when processing the response form the server. In this situation, the argument object member can be used and can take a string, a number, an object, or an array. Other optional members include a customevents handler to deal with custom, per-transaction events as opposed to the global events that are available to any and all transactions, a scope object used to set the scope of your handler functions, and a timeout count used to set the wait time before Connection aborts the transaction and assumes failure. The remaining member of the callback object is the upload handler which is of course a special handler to deal specifically with file uploads. As I already mentioned, the response object will be missing success of failure details when dealing with file uploads, however, you can still define a callback function to be executed once the upload transaction has completed.
Read more
  • 0
  • 0
  • 2364

article-image-jquery-14-dom-manipulation-methods-replacement-copying-and-removal
Packt
19 Feb 2010
5 min read
Save for later

jQuery 1.4 DOM Manipulation Methods for Replacement, Copying and Removal

Packt
19 Feb 2010
5 min read
DOM replacement These methods are used to remove content from the DOM and replace it with new content. .html() (getter) Get the HTML contents of the first element in the set of matched elements. .html() Parameters None Return value A string containing the HTML representation of the element. Description This method is not available on XML documents. In an HTML document, we can use .html() to get the contents of any element. If our selector expression matches more than one element, only the first one's HTML content is returned. Consider the following code: $('div.demo-container').html(); In order for the content of the following <div> to be retrieved, it would have to be the first one in the document. <div class="demo-container"> <div class="demo-box">Demonstration Box</div></div> The result would look like this: <div class="demo-box">Demonstration Box</div> .html() (setter) Set the HTML contents of each element in the set of matched elements. .html(htmlString).html(function) Parameters (first version) htmlString: A string of HTML to set as the content of each matched element Parameters (second version) function: A function returning the HTML content to set Return value The jQuery object, for chaining purposes. Description The .html() method is not available in XML documents. When we use .html() to set the content of elements, any content that was in those elements is completely replaced by the new content. Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div></div> We can set the HTML contents of <div class="demo-conta iner"> as follows: $('div.demo-container').html('<p>All new content. <em>You bet!</em></p>'); That line of code will replace everything inside <div class="demo-container">. <div class="demo-container"> <p>All new content. <em>You bet!</em></p></div> As of jQuery 1.4, the .html() method allows us to set the HTML content by passing in a function. $('div.demo-container').html(function() { var emph = '<em>' + $('p').length + ' paragraphs!</em>'; return '<p>All new content for ' + emph + '</p>';}); Given a document with six paragraphs, this example will set the HTML of <div class="demo-container"> to <p>All new content for <em>6 paragraphs!</em></p>. .text() (getter) Get the combined text contents of each element in the set of matched elements, including their descendants. .text() Parameters None Return value A string containing the combined text contents of the matched elements. Description Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul></div> The code $('div.demo-container').text() would produce the following result: Demonstration Box list item 1 list item 2 .text() (setter) Set the content of each element in the set of matched elements to the specified text. .text(textString).text(function) Parameters (first version) textString: A string of text to set as the content of each matched element Parameters (second version) function: A function returning the text to set as the content Return value The jQuery object, for chaining purposes. Description Unlike the .html() method, .text() can be used in both XML and HTML documents. We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <). Consider the following HTML code: <div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul></div> The code $('div.demo-container').text('<p>This is a test.</p>'); will produce the following DOM output: <div class="demo-container"> &lt;p&gt;This is a test.&lt;/p&gt;</div> It will appear on a rendered page as though the tags were exposed as follows: <p>This is a test</p> As of jQuery 1.4, the .text() method allows us to set the text content by passing in a function. $('ul li').text(function() {return 'item number ' + ($(this).index() + 1);}); Given an unordered list with three <li> elements, this example will produce the following DOM output: <ul><li>item number 1</li><li>item number 2</li><li>item number 3</li></ul>
Read more
  • 0
  • 0
  • 2063
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-jquery-14-dom-insertion-methods
Packt
19 Feb 2010
8 min read
Save for later

jQuery 1.4 DOM Insertion Methods

Packt
19 Feb 2010
8 min read
DOM insertion, inside These methods allow us to insert new content inside an existing element. .prepend() Insert content specified by the parameter at the beginning of each element in the set of matched elements. .prepend(content).prepend(function) Parameters (first version) content: An element, an HTML string, or a jQuery object to insert at the beginning of each element in the set of matched elements Parameters (second version) function: A function that returns an HTML string to insert at the beginning of each element in the set of matched elements Return value The jQuery object, for chaining purposes. Description The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax, specifically in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method either as a selector expression or as markup created on the fly. It is then inserted into the target container. Consider the following HTML code: <h2>Greetings</h2> <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> We can create content and insert it into several elements at once. $('.inner').prepend('<p>Test</p>'); Each <div class="inner"> element gets the following new content: <h2>Greetings</h2> <div class="container"> <div class="inner"> <p>Test</p> Hello </div> <div class="inner"> <p>Test</p> Goodbye </div></div> We can also select an element on the page and insert it into another: $('.container').prepend($('h2')); If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned). <div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> However, if there are more than one target elements, cloned copies of the inserted elements will be created for each target after the first. .prependTo() Insert every element in the set of matched elements at the beginning of the target. .prependTo(target) Parameters target: A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter Return value The jQuery object, for chaining purposes. Description The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax, specifically in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method either as a selector expression or as markup created on the fly, and is inserted into the target container. Consider the following HTML code: <h2>Greetings</h2> <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> We can create content and insert it into several elements at once. $('<p>Test</p>').prependTo('.inner'); Each inner <div> element gets the following new content: <h2>Greetings</h2><div class="container"> <div class="inner"> <p>Test</p> Hello </div> <div class="inner"> <p>Test</p> Goodbye </div></div> We can also select an element on the page and insert it into another. $('h2').prependTo($('.container')); If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned). <div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> However, if there are more than one target elements, cloned copies of the inserted elements will be created for each target after the first. .append() Insert content specified by the parameter at the end of each element in the set of matched elements. .append(content).append(function) Parameters (first version) content: An element, an HTML string, or a jQuery object to insert at the end of each element in the set of matched elements Parameters (second version) function: A function that returns an HTML string to insert at the end of each element in the set of matched elements Return value The jQuery object, for chaining purposes. Description The .append() and .appendTo() methods perform the same task. The major difference is in the syntax, specifically in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method either as a selector expression or as markup created on the fly, and is inserted into the target container. Consider the following HTML code: <h2>Greetings</h2><div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> We can create content and insert it into several elements at once. $('.inner').append('<p>Test</p>'); Each inner <div> element gets the following new content: <h2>Greetings</h2><div class="container"> <div class="inner"> Hello <p>Test</p> </div> <div class="inner"> Goodbye <p>Test</p> </div></div> We can also select an element on the page and insert it into another. $('.container').append($('h2')); If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned). <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> <h2>Greetings</h2></div> However, if there is more than one target element, cloned copies of the inserted elements will be created for each target after the first. .appendTo() Insert every element in the set of matched elements at the end of the target. .appendTo(target) Parameters target: A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter Return value The jQuery object, for chaining purposes. Description The .append() and .appendTo() methods perform the same task. The major difference is in the syntax, specifically in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method either as a selector expression or as markup created on the fly, and is inserted into the target container. Consider the following HTML code: <h2>Greetings</h2><div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div></div> We can create content and insert it into several elements at once. $('<p>Test</p>').appendTo('.inner'); Each inner <div> element gets the following new content: <h2>Greetings</h2> <div class="container"> <div class="inner"> Hello <p>Test</p> </div> <div class="inner"> Goodbye <p>Test</p> </div></div> We can also select an element on the page and insert it into another. $('h2').append($('.container')); If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned). <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> <h2>Greetings</h2></div> However, if there are more than one target elements, cloned copies of the inserted elements will be created for each target after the first.
Read more
  • 0
  • 0
  • 1911

article-image-building-calender-application-joomla-using-fabrik
Packt
19 Feb 2010
3 min read
Save for later

Building a Calender Application in Joomla! using Fabrik

Packt
19 Feb 2010
3 min read
Getting ready You need a working installation of Joomla! 1.5.x. For exercise purpose, you can install that on your local computer. The web server should have PHP5 installed. Then you need to install Fabrik component. This component is available for free from http://fabrikar.com/download. Download the latest version of the component and install it from Extensions | Install/Uninstall screen in Joomla! administration panel. Also plan for the application you want to develop. For example, we are developing an event calender. This event calender will contain the following information: Event Category Event Name Venue Start Date & Time End Date & Time Event Description Attached Document Created by This is a very simple list of information we need. Based on the we will create two database tables: categories and events. The table structure is shown in the following diagram. The above table diagrams show that categories table is linked to events table by foreign key category_id. Similarly, we have added user_id field in events table, so that we can link it to jos_users table. Whenever a user creates an event, his or her user ID will be added to this field. For creating the tables in Joomla! database, connect to that database using phpMyadmin or some other interface, and run the following SQL command: CREATE TABLE `categories` (`id` INTEGER AUTO_INCREMENT DEFAULT NULL ,`name` VARCHAR(200) DEFAULT NULL ,PRIMARY KEY (`id`)) COMMENT 'contains categories of events';CREATE TABLE `events` (`id` INTEGER AUTO_INCREMENT DEFAULT NULL ,`category_id` INTEGER DEFAULT NULL ,`event_name` MEDIUMTEXT DEFAULT NULL ,`venue` VARCHAR(100) DEFAULT NULL ,`start` DATETIME DEFAULT NULL ,`end` DATETIME DEFAULT NULL ,`description` MEDIUMTEXT DEFAULT NULL ,`attachment` VARCHAR(250) DEFAULT NULL ,`user_id` INTEGER DEFAULT NULL ,PRIMARY KEY (`id`)) COMMENT 'list of events';ALTER TABLE `events` ADD FOREIGN KEY (category_id) REFERENCES `categories` (`id`); Successful execution of the above code block will create two tables and add a foreign key to events table linking it to categories table. With creation of these two table we are set to create our event calendar application. How to do it... Follow the steps below: From Joomla! Administration panel, click Components | Fabrik |  Connections. That shows existing database connections. By default, connection to Joomla! database is created. You can create  new database connection by clicking New button and filling in the form. Click on Tables link in this screen. That shows existing tables created in Fabrik. In Table screen, click on New button to add a new table. That shows Table: [New] screen. In Label field type Categories, and in Introduction field, type Event Categories. Then select Yes in Published radio box to the right side. Accept default values for other fields. Then click Access tab. That shows Access Rights. Accept the default values in Access tab. Now click Data tab. From here you have to configure which data table you want to use. From Connection drop down list, select site database. Then click on Link to Table drop down list and select categories table. In Order By drop down list, select name. There are some other options in this tab, but those cannot be configured until you save the table. Now click Save button to save the table.
Read more
  • 0
  • 0
  • 3776

article-image-php-web-20-mashup-projects-your-own-video-jukebox-part-1
Packt
19 Feb 2010
11 min read
Save for later

PHP Web 2.0 Mashup Projects: Your Own Video Jukebox: Part 1

Packt
19 Feb 2010
11 min read
Project Overview What Mashup the web APIs from Last.fm and YouTube to create a video jukebox of songs Protocols Used REST (XML-RPC available) Data Formats XML, XPSF, RSS Tools Featured PEAR APIs Used Last.fm and YouTube   Now that we've had some experience using web services, it's time to fine tune their use. XML-RPC, REST, and SOAP will be frequent companions when you use web services and create mashups. You will encounter a lot of different data formats, and interesting ways in which the PHP community has dealt with these formats. This is especially true because REST has become so popular. In REST, with no formalized response format, you will encounter return formats that vary from plain text to ad-hoc XML to XML-based standards. The rest of our projects will focus on exposing us to some new formats, and we will look at how to handle them through PHP. We will begin with a project to create our own personalized video jukebox. This mashup will pull music lists feeds from the social music site, Last.fm. We will parse out artist names and song titles from these feeds and use that information to search videos on YouTube, a user-contributed video site, using the YouTube web service. By basing the song selections on ever-changing feeds, our jukebox selection will not be static, and will change as our music taste evolves. As YouTube is a user-contributed site, we will see many interesting interpretations of our music, too. This jukebox will be personalized, dynamic, and quite interesting. Both Last.fm and YouTube's APIs offer their web services through REST, and YouTube additionally offers an XML-RPC interface. Like with previous APIs, XML is returned with each service call. Last.fm returns either plain text, an XML playlist format called XSPF (XML Shareable Playlist Format), or RSS (Really Simple Syndication). In the case of YouTube, the service returns a proprietary format. Previously, we wrote our own SAX-based XML parser to extract XML data. In this article, we will take a look at how PEAR, the PHP Extension and Application Repository, can do the XSPF parsing work for us on this project and might help in other projects. Let's take a look at the various data formats we will be using, and then the web services themselves. XSPF One of XML's original goals was to allow industries to create their own markup languages to exchange data. Because anyone can create their own elements and schemas, as long as people agreed on a format, XML can be used as the universal data transmission language for that industry. One of the earliest XML-based languages was ChemXML, a language used to transmit data within the chemical industry. Since then, many others have popped up. XSPF was a complete grassroots project to create an open, non-proprietary music playlist format based on XML. Historically, playlists for software media players and music devices were designed to be used only on the machine or device, and schemas were designed by the vendor themselves. XSPF's goal was to create a format that could be used in software, devices, and across networks. XSPF is a very simple format, and is easy to understand. The project home page is at http://www.xspf.org. There, you will find a quick start guide which outlines a simple playlist as well as the official specifications at http://www.xspf.org/specs. Basically, a typical playlist has the following structure: <?xml version="1.0" encoding="UTF-8"?><playlist version="1" > <title>Shu Chow's Playlist</title> <date>2006-11-24T12:01:21Z</data> <trackList> <track> <title>Pure</title> <creator>Lightning Seeds</creator> <location> file:///Users/schow/Music/Pure.mp3 </location> </track> <track> <title>Roadrunner</title> <creator>The Modern Lovers</creator> <location> file:///Users/schow/Music/Roadrunner.mp3 </location> </track> <track> <title>The Bells</title> <creator>April Smith</creator> <location> file:///Users/schow/Music/The_Bells.mp3 </location> </track> </trackList></playlist> playlist is the parent element for the whole document. It requires one child element, trackList, but there can be several child elements that are the metadata for the playlist itself. In this example, the playlist has a title specified in the title element, and the creation date is specified in the date element. Underneath trackList are the individual tracks that make up the playlist. Each track is encapsulated by the track element. Information about the track, including the location of its file, is encapsulated in elements underneath track. In our example, each track has a title, an artist name, and a local file location. The official specifications allow for more track information elements such as track length and album information. Here are the playlist child elements summarized: Playlist Child Element Required? Description trackList Yes The parent of individual track elements. This is the only required child element of a playlist. Can be empty if the playlist has no songs. title No A human readable title of the XSPF playlist. creator No The name of the playlist creator. annotation No Comments on the playlist. info No A URL to a page containing more information about the playlist. location No The URL to the playlist itself. identifier No The unique ID for the playlist. Must be a legal Uniform Resource Name (URN). image No A URL to an image representing the playlist. date No The creation (not the last modified!) date of the playlist. Must be in XML schema dateTime format. For example, "2004-02-27T03:30:00". license No If the playlist is under a license, the license is specified with this element. attribution No If the playlist is modified from another source, the attribution element gives credit back to the original source, if necessary. link No Allows non-XSPF resources to be included in the playlist. meta No Allows non-XSPF metadata to be included in the playlist. extension No Allows non-XSPF XML extensions to be included in the playlist. A trackList element has an unlimited number of track elements to represent each track. track is the only allowed child of trackList. track's child elements give us information about each track. The following table summarizes the children of track: Track Child Element Required? Description location No The URL to the audio file of the track. identifier No The canonical ID for the playlist. Must be a legal URN. title No A human readable title of the track. Usually, the song's name. creator No The name of the track creator. Usually, the song's artist. annotation No Comments on the track. info No A URL to a page containing more information about the track. image No A URL to an image representing the track. album No The name of the album that the track belongs to. trackNum No The ordinal number position of the track in the album. duration No The time to play the track in milliseconds. link No Allows non-XSPF resources to be included in the track. meta No Allows non-XSPF metadata to be included in the track. extension No Allows non-XSPF XML extensions to be included in the track. Note that XSPF is very simple and track oriented. It was not designed to be a repository or database for songs. There are not a lot of options to manipulate the list. XSPF is merely a shareable playlist format, and nothing more. RSS The simplest answer to, "What is RSS?", is that it's an XML file used to publish frequently updated information, like news items, blogs entries, or links to podcast episodes. News sites like Slashdot.org and the New York Times provide their news items in RSS format. As new news items are published, they are added to the RSS feed. Being XML-based, third-party aggregator software makes reading news items easy. With one piece of software, I can tell it to grab feeds from various sources and read the news items in one location. Web applications can also read and parse RSS files. By offering an RSS feed for my blog, another site can grab the feed and keep track of my daily life. This is one way by which a small site can provide rudimentary web services with minimal investment. The more honest answer is that it is a group of XML standards (used to publish frequently updated information like news items or blogs) that may have little compatibility with each other. Each version release also has a tale of conflict and strife behind it. We won't dwell on the politicking of RSS. We'll just look at the outcomes. The RSS world now has three main flavors: The RSS 1.0 branch includes versions 0.90, 1.0, and 1.1. It's goal is to be extensible and flexible. The downside to the goals is that it is a complex standard. The RSS 2.0 branch includes versions 0.91, 0.92, and 2.0.x. Its goal is to be simple and easy to use. The drawback to this branch is that it may not be powerful enough for complex sites and feeds. There are some basic skeletal similarities between the two formats. After the XML root element, metadata about the feed itself is provided in a top section. After the metadata, one or more items follow. These items can be news stories, blog entries, or podcasts episodes. These items are the meat of an RSS feed. The following is an example RSS 1.1 file from XML.com: <Channel rdf_about="http://www.xml.com/xml/news.rss"> <title>XML.com</title> <link>http://xml.com/pub</link> <description> XML.com features a rich mix of information and services for the XML community. </description> <image rdf_parseType="Resource"> <title>XML.com</title> <url>http://xml.com/universal/images/xml_tiny.gif</url> </image> <items rdf_parseType="Collection"> <item rdf_about= "http://www.xml.com/pub/a/2005/01/05/restful.html"> <title> The Restful Web: Amazon's Simple Queue Service </title> <link> http://www.xml.com/pub/a/2005/01/05/restful.html </link> <description> In Joe Gregorio's latest Restful Web column, he explains that Amazon's Simple Queue Service, a web service offering a queue for reliable storage of transient messages, isn't as RESTful as it claims. </description> </item> <item rdf_about= "http://www.xml.com/pub/a/2005/01/05/tr-xml.html"> <title> Transforming XML: Extending XSLT with EXSLT </title> <link> http://www.xml.com/pub/a/2005/01/05/tr-xml.html </link> <description> In this month's Transforming XML column, Bob DuCharme reports happily that the promise of XSLT extensibility via EXSLT has become a reality. </description> </item> </items></Channel> The root element of an RSS file is an element named Channel. Immediately, after the root element are elements that describe the publisher and the feed. The title, link, description, and image elements give us more information about the feed. The actual content is nested in the items element. Even if there are no items in the feed, the items element is required, but will be empty. Usage of these elements can be summarized as follows: Channel Child Element Required? Description title Yes A human readable title of the channel. link Yes A URL to the feed. description Yes A human readable description of the feed. items Yes A parent element to wrap around item elements. image No A section to house information about an official image for the feed. others No Any other elements not in the RSS namespace can be optionally included here. The namespace must have been declared earlier, and the child elements must be prefixed. If used, the image element needs its own child elements to hold information about the feed image. A title element is required and while optional, a link element to the actual URL of the image would be extremely useful. Each news blog, or podcast entry is represented by an item element. In this RSS file, each item has a title, link, and a description, each, represented by the respective element. This file has two items in it before the items and Channel elements are closed off.
Read more
  • 0
  • 0
  • 2471

article-image-php-web-20-mashup-projects-your-own-video-jukebox-part-2
Packt
19 Feb 2010
19 min read
Save for later

PHP Web 2.0 Mashup Projects: Your Own Video Jukebox: Part 2

Packt
19 Feb 2010
19 min read
Parsing With PEAR If we were to start mashing up right now, between XSPF, YouTube's XML response, and RSS, we would have to create three different parsers to handle all three response formats. We would have to comb through the documentation and create flexible parsers for all three formats. If the XML response for any of these formats changes, we would also be responsible for changing our parser code. This isn't a difficult task, but we should be aware that someone else has already done the work for us. Someone else has already dissected the XML code. To save time, we can leverage this work for our mashup. We used PEAR, earlier in Chapter 1 to help with XML-RPC parsing. For this project, we will once again use PEAR to save us the trouble of writing parsers for the three XML formats we will encounter. For this project, we will take a look at three packages for our mashup. File_XSPF is a package for extracting and setting up XSPF playlists. Services_YouTube is a Web Services package that was created specifically for handling the YouTube API for us. Finally, XML_RSS is a package for working with RSS feeds. For this project, it works out well that there are three specific packages that fits our XML and RSS formats. If you need to work with an XML format that does not have a specific PEAR package, you can use the XML_Unserializer package. This package will take a XML and return it as a string. Is PEAR Right For You?Before we start installing PEAR packages, we should take a look if it is even feasible to use them for a project. PEAR packages are installed with a command line package manager that is included with every core installation of PHP. In order for you to install PEAR packages, you need to have administrative access to the server. If you are in a shared hosting environment and your hosting company is stingy, or if you are in a strict corporate environment where getting a server change is more hassle than it is worth, PEAR installation may not be allowed. You could get around this by downloading the PEAR files and installing them in your web documents directory. However, you will then have to manage package dependencies and package updates by yourself. This hassle may be more trouble than it's worth, and you may be better off writing your own code to handle the functionality.On the other hand, PEAR packages are often a great time saver. The purpose of the packages is to either simplify tedious tasks, or interface with complex systems. The PEAR developer has done the difficult work for you already. Moreover, as they are written in PHP and not C, like a PHP extension would be, a competent PHP developer should be able to read the code for documentation if it is lacking. Finally, one key benefit of many packages, including the ones we will be looking at, is that they are object-oriented representations of whatever they are interfacing. Values can be extracted by simply calling an object's properties, and complex connections can be ignited by a simple function call. This helps keep our code cleaner and modular. Whether the benefits of PEAR outweigh the potential obstacles depends on your specific situation. Package Installation and Usage Just like when we installed the XML-RPC package, we will use the install binary to install our three packages. If you recall, installing a package, simply type install into the command line followed by the name of the package. In this case, though, we need to set a few more flags to force the installer to grab dependencies and code in beta status. To install File_XSPF, switch to the root user of the machine and use this command: [Blossom:~] shuchow# /usr/local/php5/bin/pear install -f --alldeps File_XSPF This command will download the package. The -alldeps flag tells PEAR to also check for required dependencies and install them if necessary. The progress and outcome of the downloads will be reported. Do a similar command for Services_YouTube: [Blossom:~] shuchow# /usr/local/php5/bin/pear install -f --alldeps Services_YouTube Usually, you will not need the –f flag. By default, PEAR downloads the latest stable release of a package. The –f flag, force, forces PEAR to download the most current version, regardless of its release state. As of this writing, File_XSPF and Services_YouTube do not have stable releases, only beta and alpha respectively. Therefore, we must use –f to grab and install this package. Otherwise, PEAR will complain that the latest version is not available. If the package you want to download is in release state, you will not need the –f flag. This is the case of XML_RSS, which has a stable version available. [Blossom:~] shuchow# /usr/local/php5/bin/pear install --alldeps XML_RSS After this, sending a list-all command to PEAR will show the three new packages along with the packages you had before. PEAR packages are basically self-contained PHP files that PEAR installs into your PHP includes directory. The includes directory is a directive in your php.ini file. Navigate to this directory to see the PEAR packages' source files. To use a PEAR package, you will need to include the package's source file in the top of your code. Consult the package's documentation on how to include the main package file. For example, File_XSPF is activated by including a file named XSPF.php. PEAR places XSPF.php in a directory named File, and that directory is inside your includes directory. <?php require_once 'File/XSPF.php'; //File_XSPF is now available. File_XSPF The documentation to the latest version of XSPF is located at http://pear.php.net/package/File_XSPF/docs/latest/File_XSPF/File_XSPF.html. The package is simple to use. The heart of the package is an object called XSPF. You instantiate and use this object to interact with a playlist. It has methods to retrieve and modify values from a playlist, as well as utility methods to load a playlist into memory, write a playlist from memory to a file, and convert an XSPF file to other formats. Getting information from a playlist consists of two straightforward steps. First, the location of the XSPF file is passed to the XSPF object's parse method. This loads the file into memory. After the file is loaded, you can use the object's various getter methods to extract values from the list. Most of the XSPF getter methods are related to getting metadata about the playlist itself. To get information about the tracks in the playlist, use the getTracks method. This method will return an array of XSPF_Track objects. Each track in the playlist is represented as an XSPF_Track object in this array. You can then use the XSPF_Track object's methods to grab information about the individual tracks. We can grab a playlist from Last.fm to illustrate how this works. The web service has a playlist of a member's most played songs. Named Top Tracks, the playlist is located at http://ws.audioscrobbler.com/1.0/user/USERNAME/toptracks.xspf, where USERNAME is the name of the Last.fm user that you want to query. This page is named XSPFPEARTest.php in the examples. It uses File_XSPF to display my top tracks playlist from Last.fm. <?php require_once 'File/XSPF.php'; $xspfObj =& new File_XSPF(); //Load the playlist into the XSPF object. $xspfObj->parseFile('http://ws.audioscrobbler.com/1.0/user/ ShuTheMoody/toptracks.xspf'); //Get all tracks in the playlist. $tracks = $xspfObj->getTracks();?> This first section creates the XSPF object and loads the playlist. First, we bring in the File_XSPF package into the script. Then, we instantiate the object. The parseFile method is used to load an XSPF file list across a network. This ties the playlist to the XSPF object. We then use the getTracks method to transform the songs on the playlist into XSPF_Track objects. <html><head> <title>Shu Chow's Last.fm Top Tracks</title></head><body> Title: <?= $xspfObj->getTitle() ?><br /> Created By: <?= $xspfObj->getCreator() ?> Next, we prepare to display the playlist. Before we do that, we extract some information about the playlist. The XSPF object's getTitle method returns the XSPF file's title element. getCreator returns the creator element of the file. <?php foreach ($tracks as $track) { ?> <p> Title: <?= $track->getTitle() ?><br /> Artist: <?= $track->getCreator() ?><br /> </p><?php } ?></body></html> Finally, we loop through the tracks array. We assign the array's elements, which are XSPF_Track objects, into the $track variable. XSPF_Track also has getTitle and getCreator methods. Unlike XSPF's methods of the same names, getTitle returns the title of the track, and getCreator returns the track's artist. Running this file in your web browser will return a list populated with data from Last.fm. Services_YouTube Services_YouTube works in a manner very similar to File_XSPF. Like File_XSPF, it is an object-oriented abstraction layer on top of a more complicated system. In this case, the system is the YouTube API. Using Services_YouTube is a lot like using File_XSPF. Include the package in your code, instantiate a Services_YouTube object, and use this object's methods to interact with the service. The official documentation for the latest release of Services_YouTube is located at http://pear.php.net/package/Services_YouTube/docs/latest/. The package also contains online working examples at http://pear.php.net/manual/en/package.webservices.services-youtube.php. Many of the methods deal with getting members' information like their profile and videos they've uploaded. A smaller, but very important subset is used to query YouTube for videos. We will use this subset in our mashup. To get a list of videos that have been tagged with a specific tag, use the object's listByTag method. listByTag will query the YouTube service and store the XML response in memory. It is does not return an array of video objects we can directly manage, but with one additional function call, we can achieve this. From there, we can loop through an array of videos similar to what we did for XSPF tracks. The example file YouTubePearTest.php illustrates this process. <?php require_once 'Services/YouTube.php'; $dev_id = 'Your YouTube DeveloperID'; $tag = 'Social Distortion'; $youtube = new Services_YouTube($dev_id, array('usesCache' => true)); $videos = $youtube->listByTag($tag);?> First, we load the Services_YouTube file into our script. As YouTube's web service requires a Developer ID, we store that information into a local variable. After that, we place the tag we want to search for in another local variable named $tag. In this example, we are going to check out which videos YouTube has for the one of the greatest bands of all time, Social Distortion. Service_YouTube's constructor takes this Developer ID and uses it whenever it queries the YouTube web service. The constructor can take an array of options as a parameter. One of the options is to use a local cache of the queries. It is considered good practice to use a cache, as to not slam the YouTube server and run up your requests quota. Another option is to specify either REST or XML-RPC as the protocol via the driver key in the options array. By default, Services_YouTube uses REST. Unless you have a burning requirement to use XML-RPC, you can leave it as is. Once instantiated, you can call listByTag to get the response from YouTube. listByTag takes only one parameter—the tag of our desire. Services_YouTube now has the results from YouTube. We can begin the display of the results. <html><head> <title>Social Distortion Videos</title></head><body> <h1>YouTube Query Results for Social Distortion</h1> Next, we will loop through the videos. In order to get an array of video objects, we first need to parse the XML response. We do that using Services_YouTube's xpath method, which will use the powerful XPATH query language to go through the XML and convert it into PHP objects. We pass the XPATH query into the method, which will give us an array of useful objects. We will take a closer look at XPATH and XPATH queries later in another project. For now, trust that the query //video will return an array of video objects that we can examine. Within the loop, we display each video's title, a thumbnail image of the video, and a hyperlink to the video itself. <?php foreach ($videos->xpath('//video') as $i => $video) { ?><p> Title: <?= $video->title ?><br /> <img src='<?= $video->thumbnail_url ?>' alt='<?= $video->title ?>' /><br /> <a href='<?= $video->url ?>'>URL</a></p><?php } ?></body></html> Running this query in our web browser will give us a results page of videos that match the search term we submitted. XML_RSS Like the other PEAR extensions, XML_RSS changes something very complex, RSS, into something very simple and easy to use, PHP objects. The complete documentation for this package is at http://pear.php.net/package/XML_RSS/docs/XML_RSS. There is a small difference to the basic philosophy of XML_RSS compared to Services_YouTube and File_XSPF. The latter two packages take information from whatever we're interested in, and place them into PHP object properties. For example, File_XSPF takes track names into a Track object, and you use a getTitle() getter method to get the title of the track. In Services_YouTube, it's the same principle, but the properties are public, and so there are no getter methods. You access the video's properties directly in the video object. In XML_RSS, the values we're interested in are stored in associative arrays. The available methods in this package get the arrays, then you manipulate them directly. It's a small difference, but you should be aware of it in case you want to look at the code. It also means that you will have to check the documentation of the package to see which array keys are available to you. Let's take a look at how this works in an example. The file is named RSSPEARTest.php in the example code. One of Audioscrobbler's feeds gives us an RSS file of songs that a user recently played. The feed isn't always populated because after a few hours, songs that are played aren't considered recent. In other words, songs will eventually drop off the feed simply because they are too old. Therefore, it's best to use this feed on a heavy user of Last.fm. RJ is a good example to use. He seems to always be listening to something. We'll grab his feed from Audioscrobbler: <?php include ("XML/RSS.php"); $rss =& new XML_RSS("http://ws.audioscrobbler.com/1.0/user/RJ/ recenttracks.rss"); $rss->parse(); We start off by including the module and creating an XML_RSS object. XML_RSS is where all of the array get methods reside, and is the heart of this package. It's constructor method takes one variable—the path to the RSS file. At instantiation, the package loads the RSS file into memory. parse() is the method that actually does the RSS parsing. After this, the get methods will return data about the feed. Needless to say, parse() must be called before you do anything constructive with the file. $channelInfo = $rss->getChannelInfo();?> The package's getChannelInfo() method returns an array that holds information about the metadata, the channel, of the file. This array holds the title, description, and link elements of the RSS file. Each of these elements is stored in the array with the same key name as the element. <?= "<?xml version="1.0" encoding="UTF-8" ?>" ?> The data that comes back will be UTF-8 encoded. Therefore, we need to force the page into UTF-8 encoding mode. This line outputs the XML declaration into the top of the web page in order to insure proper rendering. Putting a regular <?xml declaration will trigger the PHP engine to parse the declaration. However, PHP will not recognize the code and halt the page with an error. <html> <head> <title><?= $channelInfo['title'] ?></title> </head> <body> <h1><?= $channelInfo['description'] ?></h1> Here we begin the actual output of the page. We start by using the array returned from getChannelInfo() to output the title and description elements of the feed. <ol> <?php foreach ($rss->getItems() as $item { ?> <li> <?= $item['title'] ?>: <a href="<?= $item ['link'] ?>"><?= $item ['link'] ?></a> </li> <?php } ?></ol> Next, we start outputting the items in the RSS file. We use getItems() to grab information about the items in the RSS. The return is an array that we loop through with a foreach statement. Here, we are extracting the item's title and link elements. We show the title, and then create a hyperlink to the song's page on Last.fm. The description and pubDate elements in the RSS are also available to us in getItems's returned array. Link to User: <a href="<?= $channelInfo['link'] ?>"><?= $channelInfo['link'] ?></a> </body></html> Finally, we use the channel's link property to create a hyperlink to the user's Last.fm page before we close off the page's body and html tags. Using More ElementsIn this example, the available elements in the channel and item arrays are a bit limited. getChannelInfo() returns an array that only has the title, description, and link properties. The array from getItems() only has title, description, link, and pubDate properties. This is because we are using the latest release version of XML_RSS. At the time of writing this book, it is version 0.9.2. The later versions of XML_RSS, currently in beta, handle many more elements. Elements in RSS 2.0 like category and authors are available. To upgrade to a beta version of XML_RSS, use the command PEAR upgrade –f XML_RSS in the command line. The –f flag is the same flag we used to force the beta and alpha installations of Service_YouTube and File_XSPF. Alternatively, you can install the beta version of XML_RSS at the beginning using the same –f flag. If we run this page on our web browser, we can see the successful results of our hit. At this point, we know how to use the Audioscrobbler feeds to get information. The majority of the feeds are either XSPF or RSS format. We know generally how the YouTube API works. Most importantly, we know how to use the respective PEAR packages to extract information from each web service. It's time to start coding our application. Mashing Up If you haven't already, you should, at the very least, create a YouTube account and sign up for a developer key. You should also create a Last.fm account, install the client software, and start listening to some music on your computer. This will personalize the video jukebox to your music tastes. All examples here will assume that you are using your own YouTube key. I will use my own Last.fm account for the examples. As the feeds are open and free, you can use the same feeds if you choose not to create a Last.fm account. Mashup Architecture There are obviously many ways in which we can set up our application. However, we're going to keep functionality fairly simple. The interface will be a framed web page. The top pane is the navigation pane. It will be for the song selection. The bottom section is the content pane and will display and play the video. In the navigation pane, we will create a select menu with all of our songs. The value, and label, for each option will be the artist name followed by a dash, followed by the name of the song (For example, "April Smith—Bright White Jackets"). Providing both pieces of information will help YouTube narrow down the selection. When the user selects a song and pushes a "Go" button, the application will load the content page into the content pane. This form will pass the artist and song information to the content page via a GET parameter. The content page will use this GET parameter to query YouTube. The page will pull up the first, most relevant result from its list of videos and display it. Main Page The main page is named jukebox.html in the example code. This is our frameset page. It will be quite simple. All it will do is define the frameset that we will use. <html><head><title>My Video Jukebox</title></head> <frameset rows="10%,90%"> <frame src="navigation.php" name="Navigation" /> <frame src="" name="Content" /> </frameset></html> This code defines our page. It is two frame rows. The navigation section, named Navigation, is 10% of the height, and the content, named Content, is the remaining 90%. When first loaded, the mashup will load the list of songs in the navigation page and nothing else.
Read more
  • 0
  • 0
  • 2167
article-image-installing-mahara
Packt
19 Feb 2010
7 min read
Save for later

Installing Mahara

Packt
19 Feb 2010
7 min read
What will you need? Before you can install Mahara, you will need to have access to a Linux server. It may be that you run Linux on a laptop or desktop at home or that your company or institution has its own Linux servers, in which case, great! If not, there are many hosting services available on the Internet, which will enable you to access a Linux server and therefore run Mahara. It is important that you get a server to which you have root access. It is also important that you set your server up with the following features: Database: Mahara must have a database to work. The databases supported are PostgreSQL Version 8.1 or later and MySQL Version 5.0.25 or later. The Mahara developers recommend that you use PostgreSQL, if possible, but for most installations, MySQL will work just as well. PHP: Mahara requires PHP Version 5.1.3 or later. Web Server: The preferred web server is Apache. PHP extensions: Compulsory Extensions: GD, JSON, cURL, libxml, SimpleXML, Session, pgSQL or Mysqli, EXIF, OpenSSL or XML-RCP (for networking support) Optional Extension: Imagick Ask your resident IT expert about the features listed above if you don't understand what they mean. A quick way to install some of the software listed above is to use the apt-get install command if you are using the Ubuntu/Debian Linux systems. See http://www.debian.org/doc/manuals/apt-howto/ to find out more. Downloading Mahara It's time for action. Let's start by seeing how easy it is for us to get a copy of Mahara for ourselves, and the best part is... it's free! Time for action – downloading Mahara Go to http://mahara.org. Click on the download button on the Mahara home page. The button will be labeled with the name of the current version of Mahara: You will now see a web page that lists all the various versions of Mahara, both previous and forthcoming versions, in Alpha and Beta. Choose the most recent version from the list in the format you prefer. We recommend that you use the .tar.gz type because it is faster to download than .zip. You will be asked if you would like to open or save the file. Select Save File, and click OK. That's all there is to it. Go to your Internet downloads folder. In there, you should see your newly downloaded Mahara package. What Just Happened? You have just taken your first step on the road to installing Mahara. We have seen the website we have to go to for downloading the most recent version and learned how to download the package in the format we prefer. Using the command line The best way of installing and administering your Mahara is to use the command line. This is a way of writing text commands to perform specific tasks, rather than having to use a graphical user interface. There are many things you can do from the command line, from common tasks such as copying and deleting files to more advanced ones such as downloading and installing software from the Internet. A lot of the things we will be doing in this section assume that you will have Secure Shell Access to your server through the terminal command line. If you have a Linux or a Mac computer, you can use the terminal on your machine to SSH into your web server. Windows users can achieve the same functionality by downloading a free terminal client called PuTTY from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html. Speak to your resident IT expert for more information on how to use the terminal, or see http://www.physics.ubc.ca/mbelab/computer/linuxintro/html/for an introduction to the Linux command line. For now, let's just learn how to get the contents of our downloaded package into the correct place on our server. Time for action – creating your Mahara file structure Copy the mahara- 1.2.0.tar.gz package you downloaded into your home directory on your web server. If you are copying the file to the server from your own computer, you can do this using the scp command (on Linux or Mac): scp mahara-1.2.0.tar.gz servername:pathtohomedirectory On Windows, you may prefer to use a free FTP utility such as FileZilla (http://filezilla-project.org/). Unpack the contents of the Mahara package on the Linux server. On the terminal, you can do this using the tar command: tar xvzf mahara-1.2.0.tar.gz You will now see a new folder called mahara-1.2.0; you will need to rename this to public. To do this on the terminal, you can use the mv command: mv mahara-1.2.0 public That's it! The Mahara code is now in place. What Just Happened? You just learned where to copy the Mahara package on your server and how to extract its contents. Creating the database A lot of the information created in your Mahara will be stored in a database. Mahara offers support for both PostgreSQL and MySQL databases. However we prefer to use PostgreSQL. If you are interested, see http://mahara.org/interaction/forum/topic.php?id=302 for a discussion on why PostgreSQL is preferred to MySQL. The way you create your database will depend on who you have chosen to host your Mahara. Sometimes, your web host will provide a graphical user interface to access your server database. Get in touch with your local IT expert to find out how to do this. However, for smaller Mahara installations, we often prefer to use something like phpPgAdmin, which is a software application that allows you to manage PostgreSQL databases over the Internet. See http://phppgadmin.sourceforge.ne for more information on setting up phpPgAdmin on your server. Also see,http://www.phpmyadmin.net/ for phpMyAdmin which works in a very similar way to phpPgAdmin but operates on a MySQL database. For now, let's get on with creating a Postgres database using our phpPgAdmin panel. Time for action – creating the Mahara database Open up your phpPgAdmin panel from your Internet browser and log in. The username is hopefully postgres. Contact your admin if you are unsure of the database password or how to locate the phyPgAdmin panel. On the front page there is a section that invites you to create database, click there. Give your database a relevant name such as mysite_Mahara. Make sure you select the UTF8 collation from the drop-down box. Finally, click Create. If you want to, it is a good idea to have a new user for each database you create. Use phpPgAdmin to create a new user. That's it, you're done! What Just Happened? We just created the database for our Mahara installation using the open source phpPgAdmin tool available for Linux. Another way to create the database on your server is to use the database command line tool. Have a go hero – using the command line to create your database Using the command line is a much more elegant way to create the database and quicker once you get the hang of it. Why not have a go at creating the database using the command line? For instructions on how to do this see the database section of the Mahara installation guide:http://wiki.mahara.org/System_Administrator%27s_Guide/Installing_Mahara Setting up the data directory Most of the data that is created in your Mahara is stored in the database. However, all the files that are uploaded by your users, such as their personal photos or documents, need to be stored in a separate place. This is where the data directory comes in. The data directory is simply a folder that holds all of the "stuff" belonging to your users. Everything is kept safe by the data directory being outside of the home directory. This set up also makes it easy for you to migrate your Mahara to another server at some point in the future. The data directory is often referred to as the dataroot.
Read more
  • 0
  • 0
  • 2362

article-image-drupal-6-performance-optimization-using-views-and-panels-caching
Packt
19 Feb 2010
5 min read
Save for later

Drupal 6 Performance Optimization Using Views and Panels Caching

Packt
19 Feb 2010
5 min read
Views caching The Views 2 module allows you to cache your Views data and content. You can cache Views data per View. We're going to enable caching on one of our existing Views, and also create a brand new View and set caching for that as well using the test content we just generated. This will show you a nice integration of the Devel functionality with the Views module and then how caching works with Views. Go to your Site building | Views configuration page and you'll see many of your default and custom views listed. We have a view on this site for our main photo gallery. The view is named photo_gallery in our View listing. Go ahead and click on one of your Views edit links to get into edit mode for a View. In our Views 2 interface mode, we'll see our tabs for default, Page, and/or Block View display. I'm going to click on my Page tab to see my View's page settings. Under my Basic settings configuration, I'll see a link for Caching. Currently, our Caching link states None, meaning that no caching has been configured for this view. Click on the None link. Select the Time-based radio button. This will enable Time-based caching for our View page. Click the Update default display button. The next caching options configuration screen will ask you to set the amount of time for both, your View Query results and for your View Rendered output. Query results refer to the amount of time raw queries should be cached. Rendered output is the amount of time the View HTML output should be cached. So basically, you can cache both your data and your frontend HTML output. Set them both to the default of 1 hour. You can also set one to a specific time and the other to None. Go ahead and tweak these settings to your own requirements. I'm leaving both set to the default of 1 hour. Click on the Update button to save your caching options settings. You are now caching your View. Save your View by clicking on the Save button. The next time you look at your View interface you should see the caching time notation listed under your Basic settings. It will say 1 hour/1 hour for this setting. Once you enable Views caching, if you make a change to your View settings and configuration, the results and output of the View may not update while you have caching enabled. So, while in Views development you may want to disable caching and set it to None. Otherwise, this next section will show you how to disable your Views cache while you are in development. To see the performance results of this, you can use the Devel module's functionality again. When you load your View after you enable caching, you should see a decrease in the amount of ms (milliseconds) needed to build your Views plugin, data, and handlers. So, if your Views plugin build loaded in 27.1 ms before you enabled caching, you may notice that it changes to something less—for example, in my case it now shows that it loads in 2.8 ms. You can immediately see a slight performance increase with your View build. Let's go ahead and build a brand new View using the test content that we generated with the Devel module and then enable caching for this View as well. Go to your Views admin and follow these steps: Add a new View. Name the View, add a description and a tag if applicable. Click on Next. I'm going to create a View that filters my blog entries and lists the new blog entries in post date order using the Devel content I generated. Add a Page display to your new View. Name the page View. Give the page View a title. Give your View an HTML list style. Set the View to display 5 posts and to use a full pager. Set your caching to Time-based (following instructions above in the first view we edited). Give the view a path. Add a Node: Title field and set the field to be linked to its node. Add a filter in order to filter by Node:Type and then select Blog entry. Set your Sort criteria to sort by Node:Post date in ascending order by hour. Your settings should look similar to this: Save your View by clicking on the Save button. Your new View will be visible at the Page path you gave it and it will also be caching the content and data it presents. Again, if you refresh your View page each time you should notice that the plugins, data, and handlers build times decrease or stay very similar and consistent in load times. You should also notice that the Devel database queries status is telling you that it's using the cached results and cached output for the View build times and the MySQL statements. You should see the following code sitting below your page content on the View page you are looking at. It will resemble this: Views plugins build time: 23.509979248 msViews data build time: 55.7069778442 msViews handlers build time: 1.95503234863 msSELECT node.nid AS nid,node_data_field_photo_gallery_photo.field_photo_gallery_photo_fidAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_fid,node_data_field_photo_gallery_photo.field_photo_gallery_photo_listAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_list,node_data_field_photo_gallery_photo.field_photo_gallery_photo_dataAS node_data_field_photo_gallery_photo_field_photo_gallery_photo_data,node.type AS node_type,node.vid AS node_vid,node.title AS node_title,node.created AS node_createdFROM {node} nodeLEFT JOIN {content_type_photo} node_data_field_photo_gallery_photo ONnode.vid = node_data_field_photo_gallery_photo.vidWHERE (node.status <> 0) AND (node.type in ('%s'))ORDER BY node_created ASCUsed cached resultsUsed cached output
Read more
  • 0
  • 0
  • 3182

article-image-jquery-14-dom-manipulation-methods-style-properties-and-class-attributes
Packt
19 Feb 2010
3 min read
Save for later

jQuery 1.4 DOM Manipulation Methods for Style Properties and Class Attributes

Packt
19 Feb 2010
3 min read
General attributes These methods get and set DOM attributes of elements. .attr() (getter) Get the value of an attribute for the first element in the set of matched elements. .attr(attributeName) Parameters attributeName: The name of the attribute to get Return value A string containing the attribute value. Description It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method. Using jQuery's .attr() method to get the value of an element's attribute has two main benefits: Convenience: It can be called directly on a jQuery object and chained to other jQuery methods. Cross-browser consistency: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies. .attr() (setter) Set one or more attributes for the set of matched elements. .attr(attributeName, value).attr(map).attr(attributeName, function) Parameters (first version) attributeName: The name of the attribute to set value: A value to set for the attribute Parameters (second version) map: A map of attribute-value pairs to set Parameters (third version) attributeName: The name of the attribute to set function: A function returning the value to set Return value The jQuery object, for chaining purposes. Description The .attr() method is a convenient and powerful way to set the value of attributes, especially when setting multiple attributes or using values returned by a function. Let's consider the following image: <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" /> Setting a simple attribute We can change the alt attribute by simply passing the name of the attribute and its new value to the .attr() method. $('#greatphoto').attr('alt', 'Beijing Brush Seller'); We can add an attribute the same way. $('#greatphoto').attr('title', 'Photo by Kelly Clark'); Setting several attributes at once To change the alt attribute and add the title attribute at the same time, we can pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute: $('#greatphoto').attr({alt: 'Beijing Brush Seller',title: 'photo by Kelly Clark'}); When setting multiple attributes, the quotation marks around attribute names are optional. Computed attribute values By using a function to set attributes, we can compute the value based on other properties of the element. For example, we could concatenate a new value with an existing value as follows: $('#greatphoto').attr('title', function() { return this.alt + ' – photo by Kelly Clark'}); This use of a function to compute attribute values can be particularly useful when we modify the attributes of multiple elements at once. .removeAttr() Remove an attribute from each element in the set of matched elements. .removeAttr(attributeName).removeAttr(function) Parameters (first version) attributeName: An attribute to remove Parameters (second version) function: A function returning the attribute to remove Return value The jQuery object, for chaining purposes. Description The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers. As of jQuery 1.4, the .removeAttr() function allows us to indicate the attribute to be removed by passing in a function.
Read more
  • 0
  • 0
  • 3462
article-image-drupal-6-performance-optimization-using-throttle-and-devel-module
Packt
19 Feb 2010
6 min read
Save for later

Drupal 6 Performance Optimization Using Throttle and Devel Module

Packt
19 Feb 2010
6 min read
Enabling and configuring the Throttle module Drupal allows you to control when your modules and blocks get enabled and shown to your site visitors. This helps you to prevent bottlenecks in your server's web traffic and to optimize your server load to prevent any congestion that it might experience with its bandwidth and traffic. Throttling blocks and modules becomes increasingly important on larger scale websites where you have many blocks and modules active. You may have a site that contains a large number of blocks, for example, that have been built with the Views module. You can throttle these blocks, so they only get enabled when the site visitor calls a page that is supposed to show that block. The throttle module allows you to configure it, so it automatically gets enabled when the usage of your site goes above a certain threshold. For example, this can be the number of anonymous users visiting your site. When a certain amount of visitors are on your site, you can have Drupal enable throttling. Using the Throttle module is essential on shared servers where you may not have all of the resources on the server made available to you at any given time or on a server that gives you limited CPU resources and bandwidth. You may not need to use Throttle on higher performance-dedicated servers because they will most likely be providing you with good performance. But on shared servers it does become important to use Throttle. If you did not enable the Throttle module after we upgraded our site to Drupal 6.13, we need to enable it first. Once enabled, we can then configure the module. Follow these steps: Under your Core-optional module list, check the box next to Throttle and then save your module configuration. There are two methods of accessing the Throttle module configuration. You can visit the main Throttle configuration page to set auto throttling settings for your site. Also, you can enable throttling for each module and block on your site. We'll look at both methods now. Note that your modules admin page explains how to access and enable both types of throttling (module and auto) at the top of the page in its introductory help text. You will only see your module throttle checkboxes available if you have enabled the Throttle module first. Configuring the Throttle module for auto throttling features Go to Site configuration | Throttle to load your Throttle module settings form or click on the throttle configuration page link through your main modules admin page. The Throttle configuration page explains what the Throttle module does and gives you a link to more information through the more help link. If you click on that link and have the Advanced Help module active, you will launch a detailed Throttle module help and explanation page. On this page you can configure three throttle elements that fall under the default Throttle module congestion control feature: Auto-throttle on anonymous users Auto-throttle on authenticated users Auto-throttle probability limiter Auto-throttle on anonymous users allows you to set a threshold for enabling your congestion control throttle dependent on anonymous user activity. So, for example, you will want to choose a threshold number of anonymous users to enter into this field. When this number of anonymous users is reached, the auto-throttle feature will be enabled. If you want the auto-throttle to be enabled after 250 anonymous users are on your site at the same time, you can type 250 into this field. Set this field to 0 if you do not want to use the auto-throttle feature. Drupal also tells you here that you can determine how many users are on your site at any given time by enabling the Who's Online block—this will show you all of the anonymous users who are browsing your site and authenticated users who are logged into your site. The Auto-throttle on authenticated users works using the same method. Add the threshold number of authenticated users that you want logged into your site before the point your throttle gets enabled. We'll set this to 50 authenticated users. The Auto-throttle probability limiter helps to reduce the overhead of the auto-throttle module. It's a built-in performance check just for this Throttle module. You can set a pe rcentage of page views for your site. For example, if you set the page view percentage to 10%, then the module will only perform extra database queries to update the Throttle module status once for every 10 page views. Drupal tells you that the busier your website, the lower you want to set this value. Leave it set to the default of 10%. Save your auto-throttle configuration. Throttling your modules You can also throttle each of your core and contributed modules as long as they have a Throttle checkbox next to their line item on the modules admin page. Load your modules admin page and look for the Throttle checkboxes. This allows you to tell Drupal to throttle a specific module during high traffic periods on your site. This means that when your site reaches a high traffic threshold (based on the auto throttling settings you determined above) your site will temporarily disable the module in question. This will throttle the module until your site returns to a stable status. You do need to be careful here. You should throttle those modules that are of lesser importance when your site reaches its threshold of user activity. When you throttle, you are temporarily disabling the module, so it will also temporarily disable that module's functionality during high server loads. So, you may want to disable some modules, such as Views, but leave your CCK module enabled so that your users can still see the content that is being filtered into the View. We'll go ahead and throttle the following modules: Administration menu (because this module is only being used by our logged in admins) Chaos tool suite (all submodules here) Comment Contact Database logging Help PHP filter Search Statistics Advanced Help FCKEditor IMCE Lightbox2 Poormanscron You can select more modules to throttle based on your preferences and the usage of your site. Use the above as an example and model to follow. Check the throttle boxes and save your configuration. During the next high server load period, these modules will be disabled temporarily to increase the performance of your site during its high server load period. Throttling blocks You can also throttle your blocks. To do this, go to the Blocks admin page here: Administer | Site building | Blocks. You'll notice that there is a new checkbox selection for Throttle. You can choose which blocks to throttle by checking the Throttle checkbox next to each of your enabled blocks. We'll go ahead and throttle all of our blocks except for the User login, as we still want to allow users to login to the site during high traffic periods. The throttle functionality works the same here as it does with modules. These blocks will be temporarily disabled during high site traffic. Once you check your throttle boxes, save your blocks configuration. The next time you have high site traffic, these blocks will be temporarily disabled.
Read more
  • 0
  • 0
  • 2869

article-image-melody-other-movable-type
Packt
19 Feb 2010
5 min read
Save for later

Melody: The Other Movable Type

Packt
19 Feb 2010
5 min read
If there’s one golden rule of open source, it’s this: Major projects can and will be forked. Multiple versions of just about every open source app of repute have been spun off from the original. These splits happen for reasons that are more often political than technical. Look at the clamor building around MySQL, where people concerned about the future of the project under Oracle’s stewardship want its code copied out into another, separately managed project that won’t (as they see it) end up as a corporate lapdog. The blogging system Movable Type, now in its fifth major revision, is also undergoing a code schism of sorts. A number of Movable Type developers and contributors became frustrated with what they felt was an emphasis by MT’s corporate owners on the wrong features, as well as a lack of transparency in the development process for the product. Rather than attack Six Apart (Movable Type’s parent company) directly, they chose instead to do an end run—to take the now open-source code base for Movable Type and create a new product from it: Melody. The theme behind Melody Melody extends on Movable Type’s legacy in four basic ways. Take what already exists in Movable Type, keep what’s best about it, remove from the core product features which make things substantially more complex but which are only used by a minority of users anyway, and move Melody forward in ways that show the developers are directly attuned to the needs of the new user (and developer) base. How these things manifest in Melody can be summed up in a few key points as shown below. Backwards compatibility Since most of the initial user base for Melody will consist of Movable Type users and developers, it only makes sense for Melody to be heavily backwards-compatible with MT. This doesn’t just mean that a MT database can be imported into a Melody installation as-is. This also means things like plugins and transformation filters will still work correctly. Both are crucial, since so much of MT’s appeal is in how it can be bent and shaped to fit user’s needs—and those same needs will carry directly over into Melody. (If anything, they’ll have to be satisfied all the better in Melody, since Melody’s being written specifically from the perspective of allowing such customization to be all the easier and more powerful to implement.) The exact degree and scope of Melody’s backwards compatibility with Movable Type is still being wrangled out, but it’s likely to be as friendly as possible to existing MT developers as a way to gain their immediate support. One thing that has become clearer is that people looking to make a straight upgrade from MT to Melody will at this point be best served by an upgrade from the 4.x branch of MT than the current 5.x branch. This is probably due to Melody being more derived from the former than the latter, but there’s nothing that says in time a clean 5.x migration path can’t be created. A more developer-friendly culture "Developer" doesn’t just mean people who write Melody or Movable Type’s own code. It means people who create the above-mentioned add-ons, and—in some ways the most visible type of third-party development—people who create themes and templates for the system. A better culture for those people to thrive in means more. Another concrete way for developer-friendliness to manifest is with better use of existing CPAN (for Perl) and jQuery (for JavaScript) libraries and community-developed code. A lot of what was written for earlier versions of Movable Type duplicated functions that were available in those repositories. Not only did this mean MT’s code had to be maintained separately, but it also meant Movable Type didn’t leverage what was available in CPAN and jQuery as effectively as it could. Indirect contribution to Movable Type itself What Melody’s developers hope to create is a project that doesn’t so much steal marketshare from Movable Type as it does give Movable Type itself a chance to become a better project, too. Melody could become a model for how MT itself might evolve, and since Melody’s licensed under the same terms as MT itself (GPLv2), there’s nothing preventing significant chunks of Melody—or even the whole project—from being back-adopted into MT. Even the Melody developers themselves don’t see everyone ditching Movable Type. For one, the enterprise-level editions of Movable Type have a bevy of features (not least among which is paid support) that won’t show up in Melody any time soon. That and Melody’s developers don’t see it as being part of their project’s focus to try and eclipse MT’s high-end, paying-customers features. (Melody’s own FAQ discourages using the paid-support add-ons for MT with Melody, because of the licensing and support-contract restrictions involved.) Melody’s current interface is based on the 4.x branch of Movable Type, and so most closely resembles that program with only minimal changes.
Read more
  • 0
  • 0
  • 2864
Modal Close icon
Modal Close icon