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
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-build-your-own-application-access-twitter-using-java-and-netbeans-part-1
Packt
05 Feb 2010
6 min read
Save for later

Build your own Application to access Twitter using Java and NetBeans: Part 1

Packt
05 Feb 2010
6 min read
Due to the fact that writing a Java app to control your Twitter account is quite a long process and requires several features, I intend to divide this article in several sections, so you can see in extreme detail all the bells and whistles involved in writing Java applications. Downloading and installing NetBeans for your developing platform To download NetBeans, open a web browser window and go to the NetBeans website. Then click on the Download button and select the All IDE download bundle. After downloading NetBeans, install it with the default options. Creating your SwingAndTweet project Open NetBeans and select File | New Project to open the New Project dialog. Now select Java from the Categories panel and Java Application from the Projects panel. Click on Next to continue. The New Java Application dialog will show up next. Type SwingAndTweet in the Project Name field, mark the Use Dedicated Folder for Storing Libraries option, deselect the Create Main Class box (we’ll deal with that later), make sure the Set as Main Project box is enabled and click on Next to continue: NetBeans will create the SwingAndTweet project and will show it under the Projects tab, in the NetBeans main window. Right click on the project’s name and select JFrame Form... in the pop-up menu: The New JFrame Form window will appear next. Type SwingAndTweetUI in the Class Name field, type swingandtweet in the Package field and click on Finish to continue: NetBeans will open the SwingAndTweetUI frame in the center panel of the main screen. Now you’re ready to assemble your Tweeter Java application! Now let me explain a little bit about what we did in the previous exercise: First, we created a new Java application called SwingAndTweet. Then we created a Swing JFrame component and we named it SwingAndTweetUI, because this is going to act as the foundation, where we’re going to put all the other Swing components required to interact with Twitter. Now I’m going to show you how to download and integrate the Twitter4J API to your SwingAndTweetJava application. Downloading and integrating the Twitter4J API into your NetBeans environment For us to be able to use the powerful classes and methods from the Twitter4J API, we need to tell NetBeans where to find them and integrate them into our Java applications. Open a web browser window, go to http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/ and search for the latest twitter4j.2.X.X.jar file, or download the most recent version at the time of this writing from here:http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/2.0.9/twitter4j-2.0.9.jar. Once you download it in your computer, go to NetBeans, right-click on the SwingAndTweet project and select Properties from the context menu. Once at the project properties screen, select the Libraries category under the Categories panel, click on the Add JAR/Folder... button at the middle-right part of the screen to open the Add JAR/Folder dialog, navigate to the directory where you downloaded the twitter4j-2.X.X.jar file and double click on it to add it to your project’s library path: Click on OK to close the Project Properties dialog and return to the NetBeans main screen. Ok, you have integrated the Twitter4J API to your SwingAndTweet application. Now, let’s see how to log into your Twitter account from our Java application... Logging into Twitter from Java and seeing your last Tweet In the following exercise, I’ll show you how easy it is to start communicating with Twitter from a Java application, thanks to the Twitter class from the Twitter4J API. You‘ll also learn how to check your last tweet through your Java application. Let’s see how to log into a Twitter account: Go to the Palette window and locate the JLabel component under the Swing Controls section; then drag and drop it into the TweetAndSwing JFrame component: Now drag a Button and a Text Editor, too. Once you have the three controls inside the SwingAndTweetUI JFrame control, arrange them as shown below: The next step is to change their names and captions, to make our application look more professional. Right click on the JLabel1 control, select Edit from the context menu, type My Last Tweet and hit Enter. Do the same procedure with the other two controls: erase the text in the jTextField1 control and type Login in the jButton1 control. Rearrange the jLabel1 and jTextField1 controls, and drag one of the ends of jTextField1 to increase its length all you can. Once done, your application will look like this: And now, let’s inject some life to our application! Double click on the JButton1 control to open your application’s code window. You’ll be inside a java method called jButton1ActionPerformed. This method will execute every time you click on the Login button, and this is where we’re going to put all the code for logging into your Twitter account. Delete the // TODO add your handling code here: line and type the following code inside the JButton1ActionPerformed method: Remember to replace username and password with your real Twitter username and password. If you look closely at the line numbers, you‘ll notice there are five error icons on lines 82, 84, 85,  88 and 89. That’s because we need to add some import lines at the beginning of your code, to indicate NetBeans where to find the Twitter and JOptionPane classes, and the TwitterException. Scroll up until you locate the package swingandtweet; line; then add the following lines: Now all the errors will disappear from your code. To see your Java application in action, press F6 or select Run  Run | Main Project from the NetBeans main menu. The Run Project window will pop up, asking you to select the main class for your project. The swingandtweet.SwingAndTweetUI class will already be selected, so just click on OK to continue. Your SwingAndTweetUI application window will appear next, showing the three controls you created. Click on the Login button and wait for the SwingAndTweet application to validate your Twitter username and password. If they’re correct, the following dialog will pop up: Click on OK to return to your SwingAndTweet application. Now you will see your last tweet on the textbox control: If you want to be really sure it’s working, go to your Twitter account and update your status through the Web interface; for example, type Testing my Java app. Then return to your SwingAndTweet application and click on the Login button again to see your last tweet. The textbox control will now reflect your latest tweet: As you can see, your SwingAndTweet Java application can now communicate with your Twitter account! Click on the X button to close the window and exit your SwingAndTweet application.
Read more
  • 0
  • 0
  • 6140

article-image-linux-e-mail-providing-webmail-access-part-1
Packt
05 Feb 2010
10 min read
Save for later

Linux E-mail: Providing Webmail Access (Part 1)

Packt
05 Feb 2010
10 min read
The webmail solution A webmail solution is a program or a series of scripts that is run on a server, is accessible over the web, and provides access to e-mail functions similar to a conventional mail client. It is used by Yahoo! Mail, Microsoft Hotmail, Microsoft Outlook Web Access, and Gmail as the primary interface to their e-mail solutions. You may already be familiar with various forms of webmail. Though we will be examining the SquirrelMail webmail solution specifically, the benefits and drawbacks of SquirrelMail apply to most webmail systems in the market. From this point of view, we will approach the issue from a general perspective, and then in detail for the SquirrelMail package. The benefits This section will focus on the advantages offered by installing and maintaining a webmail solution. As with any list, it is not entirely comprehensive. Many benefits will be specific to a particular case; it is important to carefully examine and consider how the following qualities impact your individual situation. The main benefits we will explore in this section are as follows: Easy and quick access with little or no setup Easy remote access No need to maintain client software or configuration Provision of a user interface to configure mail server options Possible security benefits Easy and quick access Although well suited to certain situations, traditional mail access solutions can often be difficult to set up and maintain. Generally, this involves installing software on a client's local computer and configuring it. This can be difficult, especially in cases where users need to set up the software themselves. Configuration can often be even more problematic as some users may not be competent enough to follow even a very detailed set of instructions. These instructions also need to be provided and maintained for many different mail clients on many different platforms. However, a webmail solution does not have most of these problems. All of the user's settings can be configured on the server as the application itself resides on the server. This translates to almost zero set up time for the user. Once they have received their login credentials, they can visit the webmail site and instantly have access to all of their mail. The user is able to access the site instantly to send and receive e-mail. As the Internet is so common now, many users will be familiar with webmail sites such as Google Mail and Windows Live Hotmail, which offer free e-mail services. However, the user interface provided by an open source package may be more primitive and lack some visual features. Squirrelmail provides access to e-mail, including the ability to send and receive attachments, and offers a good user interface. It is also worth mentioning that a webmail solution can offer what certain traditional mail clients call groupware features. These features let groups communicate and coordinate in ways that complement e-mail communication. Examples of groupware components are private calendars, shared calendars, meeting scheduling, To-do lists, and other similar tools. These applications can be preconfigured so that a user can instantly begin using them without having to configure them on their own. Several SquirrelMail plugins which implement these features are available from the SquirrelMail website. Easy remote access Another problem with traditional mail access software is that it is not portable, as an e-mail client needs to be installed and configured on a computer. Once it has been downloaded, installed, and configured on a particular computer, it is accessible only on that computer. Without webmail, users on the road will not be able to access e-mail from friends' computers, mobile devices, or Internet booths at airports. However, in a webmail solution, e-mail can be accessed from any location with an Internet connection. Employees can access their work e-mail from any computer with an Internet connection and a suitable browser. As the administrator, you can choose to permit or deny users from accessing e-mail in insecure situations. By requiring the connection to be encrypted, you can ensure that when a user is in a remote location, their communication with the server is secure. No need to maintain clients Even if software mail clients have been installed and properly configured, they must be maintained. When a new version is released, all clients must be updated. This is not necessarily an easy task. Software that does not work as expected can result in a large number of support-desk calls. Updating the software on each client can be a very large administrative burden. In fact, many expensive software packages are designed for the specific purpose of updating software on individual machines automatically. Despite this, problems specific to each local machine often arise and must be solved individually. It may also be difficult to convey instructions or notifications to remote branch locations or remote workers. With a webmail solution, this is not necessary. In contrast to this, a webmail solution is centrally maintained and administered. The webmail application resides on the server. With webmail, only the web server and the webmail package need to be upgraded. Any exceptions or problems that arise can be dealt with before or during the upgrade. The software upgrade itself can be run through on a test system before it is deployed on a live system. Although changes in settings are rare with SquirrelMail, it is possible to update a user's settings to make them compatible with the changes introduced in an updated version. Additionally, while upgrading or changing a mail server platform, testing effort can be greatly reduced as only supported browser versions need to be tested. It is advisable to mandate particular browser versions for corporate computers. In contrast with e-mail clients, there is no need to test on all of the possible clients and software platforms. Configuring mail server interface via the user interface Many traditional desktop e-mail clients provide only e-mail functionality and nothing more. Often there is no support for other essential tasks (such as changing the access password) that are performed on behalf of a mail user. Certain configuration options that reside on the server may require additional software applications or external solutions to provide for these needs. Examples of mail server options that may need to be configured include each user's password and junk mail filtering settings. In the case of the SquirrelMail webmail application, many plugins have been developed that provide these features. For example, a user is able to change his/her password directly from the webmail interface. Also, there are plugins and systems that allow users to easily sign up without any direct human intervention. This may be useful if you are interested in providing a service where users can sign up without needing an administrative overhead. Possible security benefits This issue can be seen in two different ways—it is for this reason that the title is listed as "Possible" security benefits. Nonetheless, this is still an interesting point to examine. In the software client access model, e-mail is traditionally downloaded onto the local user's computer, being stored in one or more personal folders. From a security perspective, this may be a bad thing. Users of the system may not be as conscientious or knowledgeable about computer security as a trained computer administrator might be. It is often much easier to gain unauthorized access to an end user's computer than a properly configured and secured server. The implication is that someone who stole a company laptop might be able to access all the e-mail stored on that computer. There is one more disadvantage associated with the client access model. Even if an employee is terminated, he/she may still have access to all of the e-mail that  resides on his/her local office computer. It may take a certain amount of time before important information may be secured. A disgruntled worker might easily connect an external storage source to their local office computer and download any data they desire. It is also worth noting that in a webmail model, all e-mail is centrally stored. If an attacker were to gain access to the central e-mail server, he/she might access all the e-mail stored on that server. However, it is possible that an attacker will gain access to all the e-mail if the central mail server is compromised even if a webmail system is not used. The disadvantages This section focuses on the disadvantages resulting from providing and supporting a webmail solution. The warning given in the previous section applies: This list is not entirely comprehensive. Each situation is unique, and may bring its unique disadvantages. We will go over the following disadvantages of a webmail solution: Performance issues Compatibility with large e-mail volumes Compatibility with e-mail attachments Security issues Performance The traditional e-mail client is designed in the client-server model. One mail server accepts and delivers e-mail to and from other mail servers. However, a desktop mail client can offer many additional productivity-enhancing features such as message sorting, searching, contact list management, attachment handling, along with more recent ones such as spam filtering and message encryption. Each of these features may require a certain amount of processing power. The required level of processing power may be negligible when it comes to storing one user's e-mail on a desktop computer, but providing these features may be problematic when applied on a larger scale to a single server. When examining the performance issue, it is important to consider the number of potential users that will access the webmail application and size a server accordingly. A single server may be able to easily handle something like 300 users, but if the number of users increases significantly, server load may become an issue. For example, searching through several years' archived mail may take a few seconds on a client's computer. When one user performs this task using webmail, the load will be similar. However, if many clients request this operation at short intervals or concurrently, it may be difficult for the server to process all the requests in a timely manner. This may result in pages being served at a slower rate or, in extreme circumstances, the server failing to respond. Optimally, load testing in the appropriate conditions should be performed if there is any concern that a server may not be able to handle a particular load of users. Compatibility with large e-mail volumes The webmail solution is not well suited to large mail volumes. This disadvantage is related to the previous one, but is more related to the amount of data sent. Even with a relatively low number of users, a large volume of e-mails may be difficult to manage in a webmail application. There are mainly the following two reasons for this: Firstly, every e-mail viewed and every folder listed must be sent from the server each time. With a traditional e-mail client, the client software can manage e-mail messages, creating lists and views to suit the user. However, with a webmail solution, this is performed on the server. So, if there are many users, this overhead may use a significant proportion of the server's resources. Secondly, each interaction with the webmail application requires a Hypertext Transfer Protocol (HTTP) request and response. These messages will typically be larger than those between an e-mail server and a desktop e-mail client. There may also be less parallelism when using a webmail client, inother words, fewer things going on at the same time. A desktop e-mail client may be able to check for new e-mails in several folders at the same time, but a webmail client will typically perform these tasks one after the other, if they occur automatically at all.
Read more
  • 0
  • 0
  • 2946

article-image-packaging-python-project-using-doit
Packt
05 Feb 2010
6 min read
Save for later

Packaging a Python Project using doit

Packt
05 Feb 2010
6 min read
The article won't attempt to reproduce doit documentation, but will explain how it could be used to solve a specific problem in a practical way. For a complete introduction of doit, and a description of all its features, please refer to the project documentation. Debian packaging or bazaar knowledge isn't required to follow the discussion, but it would be helpful. Background When working on a project's source code, a developer usually needs to perform different repetitive administrative tasks that are required to compile, test and distribute the source code. In general, those tasks are pretty similar from project to project; although, the details may greatly vary depending on the application type, target platform, software development cycle, etc. As a consequence, the implementation of custom scripts that automate them is needed as a part of the maintenance of the source code. Given that, this is a very common problem, many task automation tools have been created, make is one of the most well-known among them and is used as a reference to compare with other similar tools. As the reader probably knows, make provides an imperative way to automate small tasks by defining in a file (a makefile) a series of rules that have a target file, multiple dependency files and a set of commands. To reach a given target, make must ensure that target file isn't outdated and that all the dependency files are present before running the commands that will generate the target file. During this process, the evaluation of other rules might be needed to fulfill the required dependencies. Although this approach may look simple, it has been really successful in many projects for years. However, since it tries to solve a general problem, it doesn't perfectly fit in every situation. This fact has led to the creation of similar tools that attempt to address some of the drawbacks of make.: The makefile format forces the developer to learn a new mini-language. Rules are statically defined. Just one target file per rule is allowed. With the advent of dynamic programming languages, a new generation of make-like tools that solved those issues were designed. For example, rake did a really good job in providing a familiar environment for ruby developers who wanted to use an advanced task automation tool without having to learn something new other than an API. With regard to python developers, many of these tools are currently available for them with different goals in their designs. One that I find particularly interesting is doit because it doesn't have any of the make problems listed above. In particular: It's really simple to use because it uses python itself as the language to write the configuration statements needed. Tasks, the equivalent to make's rules, may have as many targets as needed, which makes things simpler when the execution of a command entails the creation of multiple files. Task themselves aren't defined in the configuration, but task generators. This is really flexible when dependencies and/or targets depend on variables that need to be evaluated at run time. The problem Let's imagine that we are working on checkbox-editor, a simple python project hosted in Launchpad that provides an easy GTK interface to write test cases for checkbox. The way the application is delivered to users is by means of .deb packages for the latest Ubuntu distributions in a Personal Package Archive or PPA, so we'd like to be able to: Package the application at any time. Install the package locally for testing. Upload the package automatically to a PPA. Fortunately, the project's trunk branch already has the configuration files needed to generate a .deb package using the usual set of tools, so we're going to focus on the process of writing the file needed to generate and upload the desired packages. Of course, since we don't like to waste our time, we only want to generate the files needed for packaging when necessary; that's is to say, we're going to follow make's approach of generating target files only when they aren't up-to-date. Tasks In this section, a file that contains the tasks generators, which are required to automate the package generation using doit, will be created step by step. The same way as a makefile is created with all the rules for make; in doit, the default file name with the task generators is dodo.py. Of course, another file name can be used by passing an argument to doit, but we'll stick to the usual name in this example. In the code snippets that will be displayed in the following sections, some global variables will be used mainly to get the name of some files. For now, just assume that they're available in the task generators methods. The code that calculates those variables value will be shown at the end of the article. Identification There are two different classes of packages: source and binary ones. Binary packages are the ones that are compiled for an specific architecture, and that are expected to be installed directly into the destination hardware without any problem. These are the type of packages that we need to generate to accomplish the goal of installing a package locally for testing purposes. Hence, two of the tasks that we need to automate are the generation of the binary package and it's installation. Source packages are useful to distribute the source code of an application in a platform independent way, so that anyone can take a look at the code, fix it or compile it for another architecture if needed. This is also the package that must be uploaded to a Launchpad PPA, since it will take care to compile it for different architectures and publish the binary packages for them. Consequently, two more tasks that should be automated are the generation of a source package and the upload to the Launchpad PPA. Before creating any package is generated, we also need to generate a copy of the source code with the latest changes. This is not absolutely needed; but it's advised since the package generation process creates some temporary files. The diagram of the tasks that have just been identified is the following: Tasks that should be automated Code The first task before any package generation is copying the source code to a new directory (for example, pkg), to keep the development directory clean from the temporary files created during the packaging process. The code that implements this task is as follows: 1 def task_code(): 2 """ 3 Create package directory and copy source files 4 (bzr branch not used to take into account uncommited changes) 5 """ 6 def copy_file(from_file, to_file): 7 dir = os.path.dirname(to_file) 8 if dir and not os.path.isdir(dir): 9 os.makedirs(dir) 10 print from_file, '=>', to_file 11 shutil.copyfile(from_file, to_file) 12 shutil.copystat(from_file, to_file) 13 return True 14 15 yield {'name': 'clean', 16 'actions': None, 17 'clean': ['rm -rf pkg']} 18 19 for target, dependency in zip(PKG_FILES, SRC_FILES): 20 yield {'name': dependency, 21 'actions': [(copy_file, (dependency, target))], 22 'dependencies': [dependency], 23 'targets': [target]}
Read more
  • 0
  • 0
  • 2137

article-image-implementing-ajax-grid-using-jquery-data-grid-plugin-jqgrid
Packt
05 Feb 2010
9 min read
Save for later

Implementing AJAX Grid using jQuery data grid plugin jqGrid

Packt
05 Feb 2010
9 min read
In this article by Audra Hendrix, Bogdan Brinzarea and Cristian Darie, authors of AJAX and PHP: Building Modern Web Applications 2nd Edition, we will discuss the usage of an AJAX-enabled data grid plugin, jqGrid. One of the most common ways to render data is in the form of a data grid. Grids are used for a wide range of tasks from displaying address books to controlling inventories and logistics management. Because centralizing data in repositories has multiple advantages for organizations, it wasn't long before a large number of applications were being built to manage data through the Internet and intranet applications by using data grids. But compared to their desktop cousins, online applications using data grids were less than stellar - they felt cumbersome and time consuming, were not always the easiest things to implement (especially when you had to control varying access levels across multiple servers), and from a usability standpoint, time lags during page reloads, sorts, and edits made online data grids a bit of a pain to use, not to mention the resources that all of this consumed. As you are a clever reader, you have undoubtedly surmised that you can use AJAX to update the grid content; we are about to show you how to do it! Your grids can update without refreshing the page, cache data for manipulation on the client (rather than asking the server to do it over and over again), and change their looks with just a few keystrokes! Gone forever are the blinking pages of partial data and sessions that time out just before you finish your edits. Enjoy! In this article, we're going to use a jQuery data grid plugin named jqGrid. jqGrid is freely available for private and commercial use (although your support is appreciated) and can be found at: http://www.trirand.com/blog/. You may have guessed that we'll be using PHP on the server side but jqGrid can be used with any of the several server-side technologies. On the client side, the grid is implemented using JavaScript's jQuery library and JSON. The look and style of the data grid will be controlled via CSS using themes, which make changing the appearance of your grid easy and very fast. Let's start looking at the plugin and how easily your newly acquired AJAX skills enable you to quickly add functionality to any website. Our finished grid will look like the one in Figure 9-1:   Figure 9-1: AJAX Grid using jQuery Let's take a look at the code for the grid and get started building it. Implementing the AJAX data grid The files and folders for this project can be obtained directly from the code download(chap:9) for this article, or can be created by typing them in. We encourage you to use the code download to save time and for accuracy. If you choose to do so, there are just a few steps you need to follow: Copy the grid folder from the code download to your ajax folder. Connect to your ajax database and execute the product.sql script. Update config.php with the correct database username and password. Load http://localhost/ajax/grid to verify the grid works fine - it should look just like Figure 9-1. You can test the editing feature by clicking on a row, making changes, and hitting the Enter key. Figure 9-2 shows a row in editing mode:     Figure 9-2: Editing a row Code overview If you prefer to type the code yourself, you'll find a complete step-by-step exercise a bit later in this article. Before then, though, let's quickly review what our grid is made of. We'll review the code in greater detail at the end of this article. The editable grid feature is made up of a few components: product.sql is the script that creates the grid database config.php and error_handler.php are our standard helper scripts grid.php and grid.class.php make up the server-side functionality index.html contains the client-side part of our project The scripts folder contains the jQuery scripts that we use in index.html   Figure 9-3: The components of the AJAX grid The database Our editable grid displays a fictional database with products. On the server side, we store the data in a table named product, which contains the following fields: product_id: A unique number automatically generated by auto-increment in the database and used as the Primary Key name: The actual name of the product price: The price of the product for sale on_promotion: A numeric field that we use to store 0/1 (or true/false) values. In the user interface, the value is expressed via a checkbox The Primary Key is defined as the product_id, as this will be unique for each product it is a logical choice. This field cannot be empty and is set to auto-increment as entries are added to the database: CREATE TABLE product( product_id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL DEFAULT '', price DECIMAL(10,2) NOT NULL DEFAULT '0.00', on_promotion TINYINT NOT NULL DEFAULT '0', PRIMARY KEY (product_id)); The other fields are rather self-explanatory—none of the fields may be left empty and each field, with the exception of product_id, has been assigned a default value. The tinyint field will be shown as a checkbox in our grid that the user can simply set on or off. The on-promotion field is set to tinyint, as it will only need to hold a true (1) or false (0) value. Styles and colors Leaving the database aside, it's useful to look at the more pertinent and immediate aspects of the application code so as to get a general overview of what's going on here. We mentioned earlier that control of the look of the grid is accomplished through CSS. Looking at the index.html file's head region, we find the following code: <link rel="stylesheet" type="text/css" href="scripts/themes/coffee/grid.css" title="coffee" media="screen" /><link rel="stylesheet" type="text/css" media="screen" href="themes/jqModal.css" /> Several themes have been included in the themes folder; coffee is the theme being used in the code above. To change the look of the grid, you need only modify the theme name to another theme, green, for example, to modify the color theme for the entire grid. Creating a custom theme is possible by creating your own images for the grid (following the naming convention of images), collecting them in a folder under the themes folder, and changing this line to reflect your new theme name. There is one exception here though, and it affects which buttons will be used. The buttons' appearance is controlled by imgpath: 'scripts/themes/green/images', found in index.html; you must alter this to reflect the path to the proper theme. Changing the theme name in two different places is error prone and we should do this carefully. By using jQuery and a nifty trick, we will be able to define the theme as a simple variable. We will be able to dynamically load the CSS file based on the current theme and imgpath will also be composed dynamically. The nifty trick involves dynamically creating the < link > tag inside head and setting the appropriate href attribute to the chosen theme. Changing the current theme simply consists of changing the theme JavaScript variable. JqModal.css controls the style of our pop-up or overlay window and is a part of the jqModal plugin. (Its functionality is controlled by the file jqModal.js found in the scripts/js folder.) You can find the plugin and its associated CSS file at: http://dev.iceburg.net/jquery/jqModal/   In addition, in the head region of index.html, there are several script src declarations for the files used to build the grid (and jqModal.js for the overlay): <script src="scripts/jquery-1.3.2.js" type="text/javascript"></script><script src="scripts/jquery.jqGrid.js" type="text/javascript"></script><script src="scripts/js/jqModal.js" type="text/javascript"></script><script src="scripts/js/jqDnR.js" type="text/javascript"></script> There are a number of files that are used to make our grid function and we will talk about these scripts in more detail later. Looking at the body of our index page, we find the declaration of the table that will house our grid and the code for getting the grid on the page and populated with our product data. <script type="text/javascript">var lastSelectedId;$('#list').jqGrid({ url:'grid.php', //name of our server side script. datatype: 'json', mtype: 'POST', //specifies whether using post or get//define columns grid should expect to use (table columns) colNames:['ID','Name', 'Price', 'Promotion'], //define data of each column and is data editable? colModel:[ {name:'product_id',index:'product_id', width:55,editable:false}, //text data that is editable gets defined {name:'name',index:'name', width:100,editable:true, edittype:'text',editoptions:{size:30,maxlength:50}},//editable currency {name:'price',index:'price', width:80, align:'right',formatter:'currency', editable:true},// T/F checkbox for on_promotion {name:'on_promotion',index:'on_promotion', width:80, formatter:'checkbox',editable:true, edittype:'checkbox'} ],//define how pages are displayed and paged rowNum:10, rowList:[5,10,20,30], imgpath: 'scripts/themes/green/images', pager: $('#pager'), sortname: 'product_id',//initially sorted on product_id viewrecords: true, sortorder: "desc", caption:"JSON Example", width:600, height:250, //what will we display based on if row is selected onSelectRow: function(id){ if(id && id!==lastSelectedId){ $('#list').restoreRow(lastSelectedId); $('#list').editRow(id,true,null,onSaveSuccess); lastSelectedId=id; } },//what to call for saving edits editurl:'grid.php?action=save'});//indicate if/when save was successfulfunction onSaveSuccess(xhr){ response = xhr.responseText; if(response == 1) return true; return false;}</script>
Read more
  • 0
  • 0
  • 16054

article-image-advanced-blog-management-apache-roller-40-part-3
Packt
03 Feb 2010
4 min read
Save for later

Advanced Blog Management with Apache Roller 4.0: Part 3

Packt
03 Feb 2010
4 min read
Weblog clients There are times when logging into your Roller weblog to post a new entry can be a tedious process, especially when you have two or more weblogs about different subjects. Let's say that you have to write stuff in your company's blog, and you also write in your personal Roller blog. You can open two web browser windows and log into each blog separately, but it would be better to use a weblog client, as I'll show you in the next exercise. Time for action – using Google docs as your weblog client In this exercise, you'll learn to use Google docs as your weblog client to post entries in your Roller weblogs without having to log in: Open your web browser, go to http://docs.google.com, log in with your username and password (if you don't have a Google account, this is your chance to get one!), then click on the New button, and select the Document option: Your browser will open a new tab for the new Google docs document. Type This is my first post to my Roller weblog from Google Docs! in the word processor writing area, as shown in the following screenshot: Now click on the File menu and select the Save option to save your draft in Google docs: Google docs assigns the title for your document automatically, based on its content. To change the title of your post, click on it: Type Posting to Roller from Google Docs in the dialog that will show up next, and click on OK to continue: Google docs will show the new title for your post: Now click on the Share button and select the Publish as web page option: The Publish this document dialog will appear. Click on the change your blog site settings link to enter your Roller weblog information: The Blog Site Settings dialog will appear next. Choose the My own server / custom option and select MetaWeblog API in the API field. In the URL field you need to type the complete path to Roller's web services—http://alromero.noip.org/roller/roller-services/xmlrpc, in my case. You just need to replace the alromero.no-ip.org part with your dynamic hostname. Then type your Roller username, password, and weblog name, and select the Include the document title when posting option, as shown in the following screenshot: Click on the OK button to save your weblog settings, and then click on the Post to blog button in the Publish this document dialog: A confirmation dialog will pop-up, asking if you want to post the document to your blog now. Click on OK to continue: Google docs will show the This document has been published to your blog success message: Click on the Save & Close button at the upper-right part of the screen to save your document and return to the Google docs main page, then click on Sign out to exit Google docs. Now go to your Roller weblog's main page, to see the post you published from Google docs: What just happened? See how easy it is to use a weblog client, so that you don't need to log into your Roller weblog to post a new entry? And if you want to post to a different Roller weblog, you just need to change your username, blog ID, or URL. There are several other weblog clients available that you can use, depending on your operating system, but all weblog clients work in a similar way. Have a go hero – try out other weblog clients Go and try out some other weblog clients, to see which one is best for you. In Windows, you can use Windows Live Writer (http://download.live.com/writer) and w.bloggar (http://bloggar.com/). In Linux, you can try out BloGTK (https://launchpad.net/blogtk/).
Read more
  • 0
  • 0
  • 1871

article-image-rendering-images-typo3-43-part-1
Packt
03 Feb 2010
4 min read
Save for later

Rendering Images in TYPO3 4.3: Part 1

Packt
03 Feb 2010
4 min read
Rendering images using content elements Content elements offer a variety of ways for editors to include images. We will examine these here. Here is a typical selection menu that editor is presented with: A great way to start is to assemble pages from the Regular text element and the Text with image elements Getting Ready Make sure Content (default) is selected in Include static, and the CSS Styled Content template is included in the Include static (from extensions) field of the template record of the current page or any page above it in the hierarchy (page tree). To verify, go to the Template module, select the appropriate page, and click edit the whole template record. How to do it... Create the Text with image element. Under the Text tab, enter the text you want to appear on the page. You can use the RTE (Rich Text Editor) to apply formatting, or disable it. We will cover RTE in more detail later in this article. Under the Media tab, select your image settings. If you want to upload the image, use the first field. If you want to use an existing image, use the second field. Under Position, you are able to select where the image will appear in relation to the text. How it works... When the page is rendered in the frontend, the images will be placed next to the text you entered, in the position that you specify. The specific look will depend on the template that you are using. There's more An alternative to the Text with images is an Images only content element. This element gives you similar options, except limits the options to just a display of images. The rest of the options are the same. You can also resize the image, add caption, alt tags for accessibility and search engine optimization, and change default processing options. See the official TYPO3 documentation for details of how these fields work, (http://typo3.org/documentation/document-library/). See also Render video and audio using content elements and rgmediaimages extension Embedding images in RTE Rich Text Editor is great for text entry. By default, TYPO3 ships with htmlArea RTE as a system extension. Other editors are available, and can be installed if needed. Images can be embedded and manipulated within the RTE. This provides one place for content editors to use in order to arrange content how they want it to appear at the frontend of the site. In this recipe, we will see how this can be accomplished. The instructions apply to all forms that have RTE-enabled fields, but we will use the text content element for a simple demonstration. In the Extension Manager, click on htmlArea RTE extension to bring up its options. Make sure that the Enable images in the RTE [enableImages] setting is enabled. If you have a recent version of DAM installed (at least 1.1.0), make sure that the Enable the DAM media browser [enableDAMBrowser] setting is unchecked. This setting is deprecated, and is there for installations using older versions of DAM. How to do it... Create a new Regular text element content element. In the RTE, click on the icon to insert an image as shown in the following screenshot: Choose a file, and click on the icon to insert it into the Text area. You should see the image as it will appear at the frontend of the site. Save and preview. The output should appear similar to the following screenshot: How it works... When you insert an image through the RTE, the image is copied to uploads folder, and included from there. The new file will be resampled and sized down, so, it usually occupies less space and is downloaded faster than the original file. TYPO3 will automatically determine if the original file has changed, and update the file used in the RTE—but you should still be aware of this behaviour. Furthermore, if you have DAM installed, and you have included an image from DAM, you can see the updated record usage. If you view the record information, you should see the Content Element where the image is used:
Read more
  • 0
  • 0
  • 2250
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 €18.99/month. Cancel anytime
article-image-advanced-blog-management-apache-roller-40-part-1
Packt
03 Feb 2010
5 min read
Save for later

Advanced Blog Management with Apache Roller 4.0: Part 1

Packt
03 Feb 2010
5 min read
So let's get on with it. Managing group blogs Suddenly, your boss bursts into your office and shouts: "Well, let's give Roller a try for our company's blog!" And now, you have to enable group blogs in your Roller installation. Time for action – creating another user The first thing you need to do in order to enable group blogging is create another user, as shown in the following exercise: Open your web browser and type your Roller's dynamic hostname in the Address bar (for example, mine is http://alromero.no-ip.org). Now click on the Login link on your weblog's main page: The Welcome to Roller page will appear. Instead of logging in, click on the Register link in order to create a new user: The New User Registration screen will show up next. Fill in the fields for your new user, as shown in the following screenshot: Click on Register User when finished. If all goes well, you'll be taken back to the Welcome to Roller screen, and the following success message will appear: Select the Click here link to continue. Type your new Username and Password, and click on the Login button. The Main Menu page will appear: Click on the Create new weblog link, under the Actions panel. Roller will take you to the Create Weblog page. Fill in the required fields to create your new weblog. Use the following data for the Name, Description, and Handle fields: The Email Address field will already contain the e-mail address you used when creating your new user. Leave the default values for Locale, Timezone, and Theme, and click on the Create Weblog button to continue. The following page will appear indicating that your weblog was successfully created: Now click on the New Entry link in order to create the following new entry in your weblog: Scroll down the page and click on the Post to Weblog button to post your entry. What just happened? Well, now there's another user in your Roller server, how about that? Your boss is going to be proud of you and very happy, because your company will have a multiuser blog! The next step is to invite other people to create user accounts and weblogs in the Roller blog server. If you're using Roller in your office, just start spreading the word to your colleagues. Or if you're experimenting with Roller in your home, you can invite some friends to blog with you, create a family group blog, and so on. Have a go hero – inviting members to write in your weblog Now that you've learned how other people can register and get a user account in Roller, it would be a good idea to start exploring the Preferences: Members page, where you can invite other Roller users to collaborate in your weblog by posting entries. Roller has three user levels: Administrator: Can create/edit weblog entries and publish them in your weblog. An administrator can also change the Roller theme and templates, and manage weblog users. Author: Can create/edit weblog entries and upload files, but cannot change themes or templates, and cannot manage users. Limited: Can create/edit entries and save them as drafts, but cannot publish them. Go on and create several test user accounts, and try out the three Roller user levels by inviting the test users to collaborate in your weblog. To invite a user, use the Invite new member link under the Actions panel in the Preferences: Members page. Enabling a front page blog Up until now, you've been using your main weblog as the front page for your Roller blog server. Now that you've enabled group blogging, each user can promote his/her weblog(s) individually, or you can create a community front page to show recent posts from all of your user's weblogs. The next exercise will show you how to create and use a front page blog to show posts from all the other weblogs in your Roller blog server. Time for action – enabling a front page blog In this exercise, we're going to create a new weblog to serve as the front page of your entire Roller weblog server. The front page blog will show a list of recent entries from all your other weblogs, and from all the other users' weblogs in your Roller blog server. Log into Roller (in case you're not already logged in) with your administrator account, go to the Main Menu page, and then click on the Create new weblog link under the Actions panel: Type My Roller Community in the Name field, The best Roller blog community in the Description field, and frontpage in the Handle field: Scroll down the page until you locate the Theme field, select the Frontpage theme, and click on the Create Weblog button: The following page will appear, indicating that your frontpage weblog was created successfully: Now click on the Server administration link located in the Actions panel. The Roller Configuration page will show up. Scroll down until you locate the Handle of weblog to serve as frontpage blog field, and replace its contents with frontpage. Then click on the Enable aggregated site-wide frontpage option to enable it: Scroll down the page until you locate the Save button and click on it to save your changes. Now click on the Front Page link in Roller's menu bar:
Read more
  • 0
  • 0
  • 1855

article-image-rendering-images-typo3-43-part-2
Packt
03 Feb 2010
4 min read
Save for later

Rendering Images in TYPO3 4.3: Part 2

Packt
03 Feb 2010
4 min read
Rendering links to files using <media> tags Imagine, for a second, a dark world of web development without content management systems. You have a simple website with some text and links to files to be downloaded. Now, imagine that you need to move the files into a different folder. You would have to go through each page, and update the links to point to the new location of the file. In DAM, the physical file is separate from the record describing the file. Thanks to this separation, the pages can link to the DAM record, instead of the physical file. If the file is moved, only the DAM record will need to be updated (which happens automatically if you move the file within DAM modules), and all links will automatically update. We will now explore how the <media> HTML tag can be used to take advantage of this feature. Getting Ready Make sure both DAM and htmlArea RTE extensions are installed. In the Extension Manager click on the DAM extension to get an overview of enable configuration. Make sure that the media tag option is enabled. How to do it... Create a new Regular text element on a page. Enter the HTML mode in the RTE: Type in <media 1234>Link text</media>, replacing 1234 with the UID of the DAM record, and link the text with the text you want to appear inside the link. You can find the UID of the record in the information panel. Save and preview. How it works... The advantage of the <media> tag is that instead of linking to a file, you're linking to a DAM record. The record, in turn, points to the physical file—so if you move the files around, all links will be updated automatically. There's more It may be possible that after enabling all the options in the Extension Manager, the <media> tags are encoded by RTE, and appear in the frontend unparsed. In that case, you need to enter the following options in Page TSconfig: // Add txdam_media to RTE processing rulesRTE.default.proc.overruleMode = ts_css,txdam_media // Use same RTE processing rules in FERTE.default.FE.proc.overruleMode = ts_css,txdam_media // RTE processing rules for bodytext column of tt_content tableRTE.config.tt_content.bodytext.proc.overruleMode = ts_css,txdam_mediaRTE.config.tt_content.bodytext.types.text.proc.overruleMode = ts_css,txdam_mediaRTE.config.tt_content.bodytext.types.textpic.proc.overruleMode = ts_css,txdam_media Accessing Page TSconfig To access Page TSconfig, right-click on a page in the page tree, and choose Edit page properties: Alternatively, you can browse to the page in the Page module, and click the Edit page properties button either in the module body, or in the docheader —the bar across the top of the module housing the control buttons. From there, the Page TSConfig, is available under the Options tab: Creating a gallery using ce_gallery There are multiple galleries available for TYPO3. Each has its own advantages, and an entire book can be dedicated to comparing the various extensions. We will install and configure only one as an example. ce_gallery has an advantage that it is very easy to set up and customize, and relies completely on DAM for content and organization. Getting Ready Make sure you have the extensions DAM and dam_catedit installed. Create a root category, and a few categories under it. Assign a few JPG images to each category How to do it... Install ce_gallery. Accept database and filesystem changes. In a template record, include the static template Photogallery (CSS) (ce_gallery). Add a Plugin content element of type Photogallery to a page. In the General tab, uncheck the Slimbox (pmkslimbox needed) checkbox. In the Categories tab, select the root category and check the box that says Recursive: Save and preview. The output should appear similar to the following screenshot: How it works... ce_gallery treats DAM categories as albums, which in turn, contain pictures. If you want to add more photos to an album, just assign them to a category, and clear cache on the page where you added the Photogallery plugin.
Read more
  • 0
  • 0
  • 1844

article-image-advanced-blog-management-apache-roller-40-part-2
Packt
03 Feb 2010
4 min read
Save for later

Advanced Blog Management with Apache Roller 4.0: Part 2

Packt
03 Feb 2010
4 min read
Enabling weblog pings Now that you have a Technorati account, let's enable your Roller weblog so that it can ping Technorati automatically each time you post a new entry or edit a previously posted entry. Time for action – enabling automatic pings in your weblog This exercise will show you how to enable automatic pinging in your weblog, so that every time you post a new entry or update some entry you posted before, Technorati will receive a ping and will update your blog status: Go to the Front Page: Weblog Settings tab in your web browser, click on the Preferences tab to see your weblog's configuration page, and click on the Pings link: The Configure Automatic Weblog Pings page will appear next. Scroll down the page until you locate the Technorati row under the Common Ping Targets section: Click on Technorati's Enable link to enable automatic pinging for your weblog, so it can send automatic pings to Technorati: Click on the Send Ping Now button to test whether everything works correctly. Roller will show the following success message: Now you just have to wait until Technorati grabs your blog's most recent information, as shown in the following screenshot: What just happened? Now Technorati will keep your weblog information updated every time you post a new entry in your weblog. Once you register with an aggregator, it's very easy to configure automatic pinging in Roller, as you saw in the previous exercise. Now all you need to do is configure all the pings you can to other aggregators and blog search engines, so that people from everywhere can see your weblog! Have a go hero – configure more ping targets Now that you learned how to configure automatic pings to Technorati for your Roller weblog, check out the other ping targets available in the Common Ping Targets list. Go on and enable all the ping targets that you can in order to promote your weblog in all the available blog search engines and aggregators. You can also register with Digg, StumbleUpon, and the other popular aggregators/blog search engines and add new ping targets for them if you click on the Custom Ping Targets link in the Configure Automatic Weblog Pings page. So what are you waiting for? Go and promote your new Roller weblog! Google webmaster tools Now that you have a cool weblog, it would be great if the weblog would show up in Google every time someone searches for a subject related to the things you're writing, don't you think? That's why Google invented the webmaster tools—a great resource to help you find out how your weblog is interacting with the Google bot. With these tools you can get detailed information about broken links, popular keywords, and basically, all the stuff you need to have a successful weblog! Time for action – enabling Google webmaster tools This exercise will show you how to configure Google webmaster tools for your Roller weblog, so you can start receiving important information about visitors and how your weblog interacts with Google: Open your web browser and type https://www.google.com/webmasters/tools to go to the Google webmaster tools website: If you created a Gmail account when installing Roller, you can use it to sign in to Google webmaster tools. Or you can create a new Gmail account in case you don't have one already. Click on the Sign In button when ready. The Google webmaster tools Home page will appear next. Click on the Add a Site button at the bottom to add your Roller weblog: Now enter your weblog's URL in the pop-up box and click on Continue: Google will show you a Meta tag that you need to copy and paste in your Roller weblog. Select the meta tag, right-click on it, and click on Copy: Now open a new tab in your web browser, log into your Roller weblog, and go to the Design tab. The Weblog Theme page will appear. Click on the Custom Theme option and then on the Update Theme button: Roller will show the Successfully set theme to – custom message. Click on the Templates link and then select the Weblog template: Scroll down the page until you locate the </head> HTML tag and paste the Google webmaster tools meta tag right before it, as shown in the following screenshot: Scroll down the page until you locate the Save button and click on it. Roller will show the Template updated successfully message. Return to the Google webmaster tools tab in your web browser and click on the Verify button to verify your weblog: If all goes well, Google will verify your weblog and take you to the Dashboard:
Read more
  • 0
  • 0
  • 2113

article-image-magentos-architecture-part-2
Packt
01 Feb 2010
7 min read
Save for later

Magento's Architecture: Part 2

Packt
01 Feb 2010
7 min read
Modules and how they work within the system Magento primarily works on a base of modules. All functionality is divided up into modules that make up the system overall. It's important to understand what each module does and how to go about adding modules to the system, in order to understand the architecture of modules themselves. Distribution of the modules between directories All modules are located within the /app/code/ directory. Directories are commonly referred to as codePools. There are three possible locations for all modules that relate to the system. They are all split by type to prevent any confusion: community—For community-distributed extensions, usually those that we have installed through Magento Connect or have downloaded from a source, other than our own. Anything installed through Magento Connect will be installed here automatically. core—Reserved for core Magento modules, so that we cannot directly overwrite or interfere with them. We keep our modules out of core to avoid any conflict with the core modules or any future updates. Anything from a Magento upgrade or any new Magento modules will go into this directory. Local—This is where we should be placing our modules when they are either under local development or are not distributed among the community. It's best to keep anything that we develop in this directory, so as to not interfere with the core or community modules. Nothing will be automatically installed here, unless we have physically uploaded it. Modules included with Magento Included modules in the core folder of default Magento installation are as follows: Mage_Admin Mage_AdminNotification Mage_Api Mage_Backup Mage_Bundle Mage_Catalog Mage_CatalogIndex Mage_CatalogInventory Mage_CatalogRule Mage_CatalogSearch Mage_Checkout Mage_Cms Mage_Contacts Mage_Core Mage_Cron Mage_Customer Mage_Dataflow Mage_Directory Mage_Downloadable Mage_Eav Mage_GiftMessage Mage_GoogleAnalytics Mage_GoogleBase Mage_GoogleCheckout Mage_GoogleOptimizer Mage_Install Mage_Log Mage_Media Mage_Newsletter Mage_Page Mage_Paygate Mage_Payment Mage_Paypal Mage_PaypalUk Mage_Poll Mage_ProductAlert Mage_Rating Mage_Reports Mage_Review Mage_Rss Mage_Rule Mage_Sales Mage_SalesRule Mage_Sendfriend Mage_Shipping Mage_Sitemap Mage_Tag Mage_Tax Mage_Usa Mage_Weee Mage_Wishlist Setting up the folder structure of a module Let's presume that we want to set up a module's folder structure, ready for development. Our module's core folders will be placed in /app/code/local/Book/Example/. These folders will primarily be used for storing our code that makes the module work. The folder structure breaks down as follows: Block/ controllers/ etc/ Model/ Mysql4/ Book/ sql/ book_setup/ Typically, developers will pick or choose each folder, depending on whether or not they're going to use it within their module. Note that Model/Mysql4/Book/ has its first letter in uppercase, whereas sql/book_setup/ does not. We must be sure to keep this the same way throughout our development. Template files for the frontend of our module will be stored as follows: XML files will be stored in /app/design/frontend/<interface>/<theme>/layout/example/ Output files will be stored in /app/design/frontend/<interface>/<theme>/template/example/ Any admin template files for the frontend of our module will be stored as follows: XML files will be stored in /app/design/adminhtml/<interface>/<theme>/layout/example/ Output files will be stored in /app/design/adminhtml/<interface>/<theme>/template/example/ Here's a breakdown of what each folder is for: Block/—For processing of all display blocks called by the system for the module. These are controllers that will be called in the XML layout files within a theme, in order to display something. controllers/—Our controllers that support the application and structurally keep things together. etc/—Configuration files for the module, for declaring things such as the default options when installed and declaring all blocks, models, and install/upgrade actions. Model/—For placement of all models to support controllers in the module. sql/—SQL actions when the module is installed/upgraded/uninstalled. Zend Framework and its role within Magento Magento (at its raw PHP base) is built on the Zend Framework. From the database class to the handling of URLs, Magento is in its raw form, with Zend Framework doing all the work. Alongside this, Varien has built several core modules on top of the Zend Framework, in order to tie it altogether into the system as we know it. What is Zend Framework Zend Framework's official site best describes the framework as follows: Zend Framework (ZF) is an open source framework for developing web applications and services with PHP 5. ZF is implemented using 100% object-oriented code. The component structure of ZF is somewhat unique; each component is designed with few dependencies on other components. This loosely coupled architecture allows developers to use components individually. We often call this a "use-at-will" design. While they can be used separately, Zend Framework components in the standard library form a powerful and extensible web application framework when combined. ZF offers a robust, high performance MVC implementation, a database abstraction that is simple to use, and a forms component that implements HTML form rendering, validation, and filtering so that developers can consolidate all of these operations using one easy-to-use, object-oriented interface. Other components, such as Zend_Auth and Zend_Acl, provide user authentication and authorization against all common credential stores. Still others implement client libraries to simply access to the most popular web services available. Whatever your application needs are, you're likely to find a Zend Framework component that can be used to dramatically reduce development time with a thoroughly tested foundation. How Zend Framework works The Zend Framework (at its core) is designed to be used as a package or separate modules. This (among other features) makes it unique, as most other frameworks are designed to be used plainly as frameworks or not at all. However, the Zend Framework comes with classes that allow us to use it as a standalone framework and develop with it as one. Instead of being delivered with a preset amount of directories and layout for developers, it only suggests a layout for our files. This means that we can adapt the framework to meet our current workflow and choose how much we adapt the workflow to fit the framework. It's role and effect in Magento The Zend Framework allows Magento to focus on the core issues at hand. It removes a lot of the work on the database and core structural classes and puts the work towards fixing and adding to core modules of Magento. Most importantly it gives developers a standard approach to development that they can move across and apply to Magento. The standard development practices help greatly in adopting Magento as a platform and make it easier for developers having experience with Zend Framework to adapt to Magento. More information on learning the Zend Framework and resources can be found at the back of this book in the Appendix attached. Its official site is located at: http://framework.zend.com/. Backing up Magento's data It's important to know how to back up our site, to ensure that our installation's data is not lost (if ever things go bad). It is recommended to back up our Magento installation: Regularly as a base to ensure that there are incremental backups of our system Before installing new modules or themes from Magento Connect When developing modules Before upgrading our system
Read more
  • 0
  • 0
  • 1998
article-image-typo3-connecting-external-apis-flicker-and-youtube
Packt
01 Feb 2010
10 min read
Save for later

TYPO3 for Connecting External APIs: Flicker and Youtube

Packt
01 Feb 2010
10 min read
Getting recent Flickr photos The Flickr API is very powerful and gives access to just about everything a user can do manually. You can write scripts to automatically download latest pictures from a photostream, download photos or videos tagged with a certain keyword, or post comments on photos. In this recipe, we will make use of the phpFlickr library to perform some basic listing functions for photos in Flickr. Getting ready Before you start, you should sign up for a free Flickr account, or use an existing one. Once you have the account, you need to sign up for an API key. You can go to Your Account, and select the Extending Flickr tab. After filling in a short form, you should be given two keys—API key and secret key. We will use these in all Flickr operations. We will not go through the steps required for integration into extensions, and will leave this exercise to the reader. The code we present can be used in both frontend plugins and backend modules. As was previously mentioned, we will be using the phpFlickr library. Go to http://phpflickr.com/ to download the latest version of the library and read the complete documentation. How to do it... Include phpFlickr, and instantiate the object (modify the path to the library, and replace api-key with your key): require_once("phpFlickr.php");$flickrService = new phpFlickr('api-key'); Get a list of photos for a specific user: $photos = $flickrService->people_getPublicPhotos('7542705@N08'); If the operation succeeds, $photos will contain an array of 100 (by default) photos from the user. You could loop over the array, and print a thumbnail with a link to the full image by: foreach ($photos['photos']['photo'] as $photo) { $imgURL = $flickrService->buildPhotoURL($photo, 'thumbnail'); print '<a href="http://www.flickr.com/photos/' . $photo['owner'] . '/' . $photo['id'] . '">' . '<img src="' . $imgURL . '" /></a><br />';} How it works... The Flickr API is exposed as a set of REST services, which we can issue calls to. The tough work of signing the requests and parsing the results is encapsulated by phpFlickr, so we don't have to worry about it. Our job is to gather the parameters, issue the request, and process the response. In the example above, we got a list of public photos from a user 7542705@N08. You may not know the user ID of the person you want to get photos for, but Flickr API offers several methods for finding the ID: $userID = $flickrService->people_findByEmail($email);$userID = $flickrService->people_findByUsername($username); If you have the user ID, but want to get more information about the user, you can do it with the following calls: // Get more info about the user:$flickrService->people_getInfo($userID);// Find which public groups the user belongs to:$flickrService->people_getPublicGroups($userID);// Get user's public photos:$flickrService->people_getPublicPhotos($userID); We utilize the people_getPublicPhotos method to get the user's photostream. The returned array has the following structure: Array( [photos] => Array ( [page] => 1 [pages] => 8 [perpage] => 100 [total] => 770 [photo] => Array ( [0] => Array ( [id] => 3960430648 [owner] => 7542705@N08 [secret] => 9c4087aae3 [server] => 3423 [farm] => 4 [title] => One Cold Morning [ispublic] => 1 [isfriend] => 0 [isfamily] => 0 ) […] ) )) We loop over the $photos['photos']['photo'] array, and for each image, we build a URL for the thumbnail using the buildPhotoURL method, and a link to the image page on Flickr. There's more... There are lots of other things we can do, but we will only cover a few basic operations. Error reporting and debugging Occasionally, you might encounter an output you do not expect. It's possible that the Flickr API returned an error, but by default, it's not shown to the user. You need to call the following functions to get more information about the error: $errorCode = $flickrService->getErrorCode();$errorMessage = $flickrService->getErrorMsg(); Downloading a list of recent photos You can get a list of the most recent photos uploaded to Flickr using the following call: $recentPhotos = $flickrService->photos_getRecent(); See also Uploading files to Flickr Uploading DAM files to Flickr Uploading files to Flickr In this recipe, we will take a look at how to upload files to Flickr, as well as how to access other authenticated operations. Although many operations don't require authentication, any interactive functions do. Once you have successfully authenticated with Flickr, you can upload files, leave comments, and make other changes to the data stored in Flickr that you wouldn't be allowed to do without authentication. Getting ready If you followed the previous example, you should have everything ready to go. We'll assume you have the $flickrService object instantiated ready. How to do it... Before calling any operations that require elevated permissions, the service needs to be authenticated. Add the following code to perform the authentication: $frob = t3lib_div::_GET('frob');if (empty($frob)) { $flickrService->auth('write', false);} else { $flickrService->auth_getToken($frob);} Call the function to upload the file: $flickrService->sync_upload($filePath); Once the file is uploaded, it will appear in the user's photostream. How it works... Flickr applications can access any user's data if the user authorizes them. For security reasons, users are redirected to Yahoo! to log into their account, and confirm access for your application. Once your application is authorized by a user, a token is stored in Flickr, and can be retrieved at any other time. $flickrService->auth() requests permissions for the application. If the application is not yet authorized by the user, he/she will be redirected to Flickr. After giving the requested permissions, Flickr will redirect the user to the URL defined in the API key settings. The redirected URL will contain a parameter frob. If present, $flickrService->auth_getToken($frob); is executed to get the token and store it in session. Future calls within the session lifetime will not require further calls to Flickr. If the session is expired, the token will be requested from Flickr service, transparent to the end user. There's more... Successful authentication allows you to access other operations that you would not be able to access using regular authentication. Gaining permissions There are different levels of permissions that the service can request. You should not request more permissions than your application will use. API call Permission level $flickrService->auth('read', false); Permissions to read users' files, sets, collections, groups, and more. $flickrService->auth('write', false); Permissions to write (upload, create new, and so on). $flickrService->auth('delete', false); Permissions to delete files, groups, associations, and so on. Choosing between synchronous and asynchronous upload There are two functions that perform a file upload: $flickrService->sync_upload($filePath);$flickrService->async_upload($filePath); The first function continues execution only after the file has been accepted and processed by Flickr. The second function returns after the file has been submitted, but not necessarily processed. Why would you use the asynchronous method? Flickr service may have a large queue of uploaded files waiting to be processed, and your application might timeout while it's waiting. If you don't need to access the uploaded file right after it was uploaded, you should use the asynchronous method. See also Getting recent Flickr photos Uploading DAM files to Flickr Uploading DAM files to Flickr In this recipe, we will make use of our knowledge of the Flickr API and the phpFlickr interface to build a Flickr upload service into DAM. We will create a new action class, which will add our functionality into a DAM file list and context menus. Getting ready For simplicity, we will skip the process of creating the extension. You can download the extension dam_flickr_upload and view the source code. We will examine it in more detail in the How it works... section. How to do it... Sign up for Flickr, and request an API key if you haven't already done so. After you receive your key, click Edit key details. Fill in the application title and description as you see fit. Under the call back URL, enter the web path to the dam_flickr_upload/mod1/index.php file. For example, if your domain is http://domain.com/, TYPO3 is installed in the root of the domain, and you installed dam_flickr_upload in the default local location under typo3conf, then enter http://domain.com/typo3conf/ext/dam_flickr_upload/mod1/index.php You're likely to experience trouble with the callback URL if you're doing it on a local installation with no public URI. Install dam_flickr_upload. In the Extension Manager, under the extension settings, enter the Flickr API key and the secret key you have received. Go to the Media | File module, and click on the control button next to a file. Alternatively, select Send to Flickr in the context menu, which appears if you click on the file icon, as seen in the following screenshot: A new window will open, and redirect you to Flickr, asking you to authorize the application for accessing your account. Confirm the authorization by clicking the OK, I'LL AUTHORIZE IT button. The file will be uploaded, and placed into your photostream on Flickr. Subsequent uploads will no longer need explicit authorization. A window will come up, and disappear after the file has been successfully uploaded. How it works... Let's examine in detail how the extension works. First, examine the file tree. The root contains the now familiar ext_tables.php and ext_conf_template.txt files.The Res directory contains icons used in the DAM. The Lib directory contains the phpFlickr library. The Mod1 directory contains the module for uploading. ext_conf_template.txt This file contains the global extension configuration variables. The two variables defined in this file are the Flickr API key and the Flickr secret key. Both of these are required to upload files. ext_tables.php As was mentioned previously, ext_tables.php is a configuration file that is loaded when the TYPO3 framework is initializing. tx_dam::register_action ('tx_dam_action_flickrUpload', 'EXT:dam_flickr_upload/class.tx_dam_flickr_upload_action.php:&tx_dam_flickr_upload_action_flickrUpload'); This line registers a new action in DAM. Actions are provided by classes extending the tx_dam_actionbase class, and define operations that can be performed on files and directories. Examples of actions include view, cut, copy, rename, delete, and more. The second parameter of the function defines where the action class is located. $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dam_flickr_upload']['allowedExtensions'] = array('avi', 'wmv', 'mov', 'mpg', 'mpeg','3gp', 'jpg', 'jpeg', 'tiff', 'gif', 'png'); We define an array of file types that can be uploaded to Flickr. This is not hardcoded in the extension, but stored in ext_tables.php, so that it can be overwritten by extensions wanting to limit or expand the functionality to other file types.
Read more
  • 0
  • 0
  • 2760

article-image-magentos-architecture-part-1
Packt
01 Feb 2010
5 min read
Save for later

Magento's Architecture: Part 1

Packt
01 Feb 2010
5 min read
Magento's base structure The fundamental knowledge of Magento's architecture begins with its file structure. It's important to know what goes where by default, so that we may position our new files accordingly, especially in terms of ensuring that our development doesn't overwrite core files. Base directory The default installation contains the following files and directories in the base directory: .htaccess .htaccess.sample 404 (directory) app (directory) cron.php downloader (directory) favicon.ico index.php index.php.sample js (directory) lib (directory) LICENSE_AFL.txt LICENSE.txt media (directory) pear pkginfo (directory) report (directory) skin (directory) var (directory) Each of these files and directories has a different purpose. We'll go through them to ensure that we understand the function of each. This will help us later, if ever we need to find something specific, or when developing. It will also be helpful when we'll be looking to place the files coming out of our new module into the appropriate directory. The function of each of the files in the base directory The following is a run through of all the files in the base directory, to show us what they do: .htaccess—This file controls mod_rewrite for fancy URLs and sets configuration server variables (such as memory limit) and PHP maximum execution time, so that Magento can run better. .htaccess.sample—Works as a backup for .htaccess, so that we know the default .htaccess file (if ever we edit it and need to backtrack). cron.php—The file that should be executed as a cron job every few minutes to ensure that Magento's wide caching doesn't affect our server's performance. favicon.ico—Magento's default favicon; it's the small icon that appears in the toolbar of our browser. index.php—The main loader file for Magento and the file that initializes everything. index.php.sample—The base template for new index.php files, useful when we have edited the index.php file and need to backtrack. LICENSE_AFL.txt—It contains the Academic Free License that Magento is distributed under. LICENSE.txt—It contains the Open Software License that Magento is distributed under. pear—This controls all automatic updating via the downloader and SSH. This file is initialized and handles the updating of each individual module that makes up Magento. php.ini—A sample php.ini file for raw PHP server variables recommended when setting up Magento on our server. This should not be used as a complete replacement, but only as a guide to replace certain lines of the php.ini server file. It is useful when overriding these variables when .htaccess isn't enabled on our server. The function of each of the folders in the base directory The following is a run through of all the folders in the base directory to show us their contents: 404—The default 404 template and skin storage folder for Magento. app—All code (modules), design (themes), configuration, and translation files are stored in this directory. This is the folder that we'll be working in extensively, when developing a Magento powered website. Also contained in this folder are the template files for the default administration theme and installation. downloader—The web downloader for upgrading and installing Magento without the use of SSH. js—The core folder where all JavaScript code included with the installation of Magento is kept. We will find all pre-compiled libraries of JavaScript here. lib—All PHP libraries used to put together Magento. This is the core code of Magento that ties everything together. The Zend Framework is also stored within this directory. media—All media is stored here. Primarily for images out of the box, this is where all generated thumbnails and uploaded product images will be stored. It is also the container for importing images, when using the mass import/export tools. pkginfo—Short form of package information, this directory contains text files that largely operate as debug files to inform us about changes when modules are upgraded in any way. report—The skin folder for the reports that Magento outputs when any error occurs. skin—All assets for themes are stored within this directory. We typically find images, JavaScript files, CSS files, and Flash files relating to themes, in this directory. However, it can be used to store any assets associated with a theme. It also contains the skin files for the installation of skins and administration templates. var—Typically where we will find all cache and generated files for Magento. We can find the cache, sessions (if storing as files), data exports, database backups, and cached error reports in this folder. The template system architecture The template architecture is broken into three areas—two for development of the theme and one for the containment of the assets: /app/design/frontend/default/<template_name>/ layout/—For all the XML files declaring which module tied functions should be called to which template files template/—For all the templates processing the output that is passed from functions called from layout/ and structured into the final output to the user. /skin/frontend/default/<template_name>/—For the containment of all assets relating to our template, images, CSS, Flash, and JavaScript. Structural blocks and content blocks Each theme contains structural and content blocks. Structural blocks are the ones that lay out the theme into sections. Let's take a look at a three-column layout. The following are the structural blocks in a three-column layout: header left content right footer Here's a visual representation of those structural blocks laid over the Magento demo store: In each of the structural blocks, we then have content blocks that give each structural block its content for output to the browser. Let's take the right column; our content blocks set for this column on a standard theme could be: mini cart recently viewed products newsletter subscription block poll
Read more
  • 0
  • 0
  • 6646

article-image-migrating-mysql-table-using-oracle-sql-developer-15
Packt
29 Jan 2010
4 min read
Save for later

Migrating a MySQL table using Oracle SQL Developer 1.5

Packt
29 Jan 2010
4 min read
Oracle SQL Developer Tool is a stand alone graphic database developer tool that connects to Oracle as well as third-party databases which can be used to perform a variety of tasks from running simple queries to migration of databases from third party vendor products to Oracle. This article by Dr. Jayaram Krishnaswamy, shows how the reader may use Oracle's most recent tool, the Oracle SQL Developer 1.5 to work with the MySQL database. An example of migrating a table in MySQL to Oracle 10G XE is also described. The Oracle SQL Developer Tool has steadily improved from its beginnings in version 1.1. The earlier versions are briefly explained here. The latest version, SQL Developer 1.5.4 released in March 2009 was described in this article. The SQL Developer tool[(1.5.4.59.40)] bundle can be downloaded from Oracle's web site, Oracle Technology Products. When you unzip the bundle you are ready to start using this tool. You may get an even more recent version of this tool as it is continuously updated. It is assumed that you have a MySQL Server that you can connect to and that you have the required credentials. The MySQL server used in developing this article was installed when the XAMPP bundle was installed. Reader will benefit by reading earlier MySQL articles 1, 2, 3 on the Packt site. Connecting to MySQL Out of the box Oracle SQL Developer 1.5.4 only supports Oracle and MS Access. The product documents clearly says that it can connect to other database products. This article will show how this is achieved. In order to install products from Oracle you must have username and password for the Oracle web Account. Bring up the Oracle SQL Developer application by clicking the executable. The program starts up and after a while the user interface gets displayed as shown. Right click on Connection, the New Connection page opens as shown displaying the default connection to the resident Oracle 10G XE server. Click the menu item Help and choose "Check for Updates". This brings up the wizard displaying the Welcome screen as shown in the next figure. Click Next. The "Source" page of the wizard shows up as shown. The updates for Oracle SQL Developer is already chosen. Place a check mark for "Third Party SQL Developer Extensions". You can choose to install looking for updates on the internet or from the downloaded bundle, if it exists. First try the internet and click Next. This brings up the "Updates" page of the wizard as shown in the next figure. Read the warning on this window. The extensions are not evaluated by Oracle but available. The details of available extensions are as follows: OrindaBuild Java Code Generator version 6.1.20090331 shown in the next figure. The JTDS DBC Driver version 11.1.58.17 shown in the next figure. The MYSQL JDBC driver shown in the next figure: The last one is a patch for the Oracle SQL Developer to fix some of the import, LDAP and performance issues as shown. For this article only the JTDS JDBC driver for MS SQL Server and the MySQL JDBC options were checked. The License agreements are for the JTDS drivers. Click Next. The License agreements must be accepted. Click I Agree. Click Next. This is the download step of the wizard. To proceed further you must have the Oracle Web Account username and password. Here you have the option to signup as well. After a while the new extensions are downloaded as shown in the next figure. Click Finish to close the wizard. You need to restart SQL Developer to complete the installation of the extensions. Click Yes on the "Confirm Exit" window that shows up. Now, when you click New Connection to create a new connection you display the "New / Select Database Connection" as shown. You can now see that other 3rd party databases are added to the window. Choose the tab for MySQL. Fill in the required details as shown in the next figure appropriate for your MySQL installation. You must provide a name for the connection. Herein the connection is named, My_MySQL. The credentials must be provided as shown or that which is appropriate for your installation. The port is the default designated for this server when you install the product. You may accept the other defaults on this page and click Test. The word "success" gets displayed in the status label at bottom left. The connection name and connection details gets added to the page shown above.
Read more
  • 0
  • 0
  • 8687
article-image-methods-animation-effects-jquery-14
Packt
29 Jan 2010
6 min read
Save for later

Methods for Animation Effects with jQuery 1.4

Packt
29 Jan 2010
6 min read
Some of the examples in this article use the $.print() function to print results to the page. Pre-packaged effects These methods allow us to quickly apply commonly-used effects with a minimum of configuration. .show() Display the matched elements. .show([duration][, callback]) Parameters duration (optional): A string or number determining how long the animation will run callback (optional): A function to call once the animation is complete Return value The jQuery object, for chaining purposes. Description With no parameters, the .show() method is the simplest way to display an element. $('.target').show(); The matched elements will be revealed immediately with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. When a duration is provided, .show() becomes an animation method. The .show() method animates the width, height, and opacity of the matched elements simultaneously. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> With the element initially hidden, we can show it slowly. $('#clickme').click(function() {$('#book').show('slow', function() {$.print('Animation complete.');});}); .hide() Hide the matched elements. .hide([duration][, callback]) Parameters duration (optional): A string or number determining how long theanimation will run callback (optional): A function to call once the animation is complete Return value The jQuery object, for chaining purposes. Description With no parameters, the .hide() method is the simplest way to hide an element. $('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, and then is hidden and shown, it will once again be displayed inline. When a duration is provided, .hide() becomes an animation method. The .hide() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the display style property is set to none to ensure that the element no longer affects the layout of the page. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> With the element initially shown, we can hide it slowly. $('#clickme').click(function() {$('#book').hide('slow', function() {$.print('Animation complete.');});}); .toggle() Display or hide the matched elements. .toggle([duration][, callback]).toggle(showOrHide) Parameters (first version) duration (optional): A string or number determining how long the animation will run callback (optional): A function to call once the animation is complete Parameters (second version) showOrHide: A Boolean indicating whether to show or hide the elements Return value The jQuery object , for chaining purposes. Description With no parameters, the .toggle() method simply toggles the visibility of elements: $('.target').toggle(); The matched elements will be revealed or hidden immediately with no animation. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. When a duration is provided, .toggle() becomes an animation method. The .toggle() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the display style property is set to none to ensure that the element no longer affects the layout of the page. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> We will cause .toggle() to be called when another element is clicked. $('#clickme').click(function() {$('#book').toggle('slow', function() {$.print('Animation complete.');});}); With the element initially shown, we can hide it slowly with the first click: A second click will show the element once again: The second version of the method accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden. In essence, the following statement $('#foo').toggle(showOrHide); is equivalent to: if (showOrHide) {$('#foo').show();}else {$('#foo').hide();} There is also an event method named .toggle().
Read more
  • 0
  • 0
  • 2512

article-image-enhancing-user-experience-php-5-ecommerce-part-3
Packt
29 Jan 2010
8 min read
Save for later

Enhancing the User Experience with PHP 5 Ecommerce: Part 3

Packt
29 Jan 2010
8 min read
Help! It's out of stock! If we have a product that is out of stock, we need to make it possible for our customers to sign up to be alerted when they are back in stock. If we don't do this, then they will be left with the option of either going elsewhere, or regularly returning to our store to check on the stock levels for that particular product. To try and discourage these customers from going elsewhere a "tell me when it is back in stock" option saves them the need to regularly check back, which would be off-putting. Of course, it is still likely that the customer may go elsewhere; however, if our store is niche, and the products are not available elsewhere, then if we give the customer this option they will feel more valued. There are a few stages involved in extending our framework to support this: Firstly, we need to take into account stock levels. If a product has no stock, we need to insert a new template bit with an "alert me when it is back in stock" form. We need a template to be inserted when this is the case. We then need functionality to capture and store the customer's e-mail address, and possibly their name, so that they can be informed when it is back in stock. Next, we need to be able to inform all of the customers who expressed an interest in a particular product when it is back in stock. Once our customers have been informed of the new stock level of the product, we need to remove their details from the database to prevent them from being informed at a later stage that there are more products in stock. Finally, we will also require an e-mail template, which will be used when sending the e-mail alerts to our customers. Detecting stock levels With customizable products, stock levels won't be completely accurate. Some products may not require stock levels, such as gift vouchers and other non-tangible products. To account for this, we could either add a new field to our database to indicate to the framework that a products stock level isn't required for that particular product, or we could use an extreme or impossible value for the stock level, for example -1 to indicate this. Changing our controller We already have our model set to pull the product stock level from the database; we just need our controller to take this value and use different template bits where appropriate. We could also alter our model to detect stock levels, and if stock is required for a product. if( $productData['stock'] == 0 ){$this->registry->getObject('template')->addTemplateBit( 'stock', 'outofstock.tpl.php' );}elseif( $productData['stock'] > 0 ){$this->registry->getObject('template')->addTemplateBit( 'stock', 'instock.tpl.php' );}else{$this->registry->getObject('template')->getPage()->addTag( 'stock', '' );} This simple code addition imports a template file into our view, depending on the stock level. Out of stock: a new template bit When the product is out of stock, we need a template to contain a form for the user to complete, so that they can register their interest in that product. <h2>Out of stock!</h2><p>We are <strong>really</strong> sorry, but this product is currentlyout of stock. If you let us know your name and email address, wewill let you know when it is back in stock.</p><form action="products/stockalert/{product_path}" method="post"><label for="stock_name">Your name</label><input type="text" id="stock_name" name="stock_name" /><label for="stock_email">Your email address</label><input type="text" id="stock_email" name="stock_email" /><input type="submit" id="stock_submit" name="stock_submit"value="Let me know, when it is back in stock!" /></form> Here we have the form showing our product view, allowing the customer to enter their name and e-mail address: Tell me when it is back in stock please! Once a customer has entered their name, e-mail address, and clicked on the submit button, we need to store these details and associate them with the product. This is going to involve a new database table to maintain the relationship between products and customers who wish to be notified when they are back in stock. Stock alerts database table We need to store the following information in the database to manage a list of customers interested in being alerted when products are back in stock: Customer name Customer e-mail address Product In terms of a database, the following table structure would represent this: Field Type Description ID Integer (Primary Key, Auto Increment) The ID for the stock alert request Customer Varchar The customer's name Email Varchar The customer's e-mail address ProductID Integer The ID of the product the customer wishes to be informed about when it is back in stock The following SQL represents this table: CREATE TABLE `product_stock_notification_requests` (`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`customer` VARCHAR( 100 ) NOT NULL ,`email` VARCHAR( 255 ) NOT NULL ,`product` INT NOT NULL ,`processed` BOOL NOT NULL ,INDEX ( `product` , `processed` )) ENGINE = INNODB COMMENT = 'Customer notification requests fornew stock levels'ALTER TABLE `product_stock_notification_requests` ADD FOREIGN KEY ( `product` ) REFERENCES `book4`.`content` (`ID`)ON DELETE CASCADE ON UPDATE CASCADE  More controller changes Some modifications are needed to our product's controller to process the customer's form submission and save it in the stock alerts database table. In addition to the following code, we must also change our switch statement to detect that the customer is visiting the stockalert section, and that the relevant function should be called. private function informCustomerWhenBackInStock(){$pathToRemove = 'products/stockalert/';$productPath = str_replace( $pathToRemove, '', $this->registry->getURLPath() );require_once( FRAMEWORK_PATH . 'models/products/model.php');$this->model = new Product( $this->registry, $productPath ); Once we have included the model and checked that the product is valid, all we need to do is build our insert array, containing the customer's details and the product ID, and insert it into the notifications table. if( $this->model->isValid() ){ $pdata = $this->product->getData(); $alert = array(); $alert['product'] = $pdata['ID']; $alert['customer'] = $this->registry->getObject('db')-> sanitizeData( $_POST['stock_name'] ); $alert['email'] = $this->registry->getObject('db')-> sanitizeData( $_POST['stock_email'] ); $alert['processed'] = 0; $this->registry->getObject('db')-> insertRecords('product_stock_notification_requests', $alert ); // We then inform the customer that we have saved their request. $this->registry->getObject('template')->getPage()-> addTag('message_heading', 'Stock alert saved'); $this->registry->getObject('template')->getPage()-> addTag('message_heading', 'Thank you for your interest in this product, we will email you when it is back in stock.'); $this->registry->getObject('template')-> buildFromTemplates('header.tpl.php', 'message.tpl.php', 'footer.tpl.php');} If the product wasn't valid, we tell them that, so they know the notification request was not saved. else{ $this->registry->getObject('template')->getPage()-> addTag('message_heading', 'Invalid product'); $this->registry->getObject('template')->getPage()-> addTag('message_heading', 'Unfortunately, we could not find the product you requested.'); $this->registry->getObject('template')-> buildFromTemplates('header.tpl.php', 'message.tpl.php', 'footer.tpl.php');}} This code is very basic, and does not validate e-mail address formats, something which must be done before we try to send any e-mails out. It is back! Once the product is back in stock, we need to then alert those customers that the product which they were interested in is back in stock, and that they can proceed to make their purchase. This isn't something we can implement now, as we don't have an administrative interface in place yet. However, we can discuss what is involved in doing this: The administrator alters the stock level. Customers interested in that product are looked up. E-mails for each of those customers are generated with relevant details, such as their name and the name of the product being automatically inserted. E-mails are sent to the customers. The database contains a processed field, so once an e-mail is sent, we can set the processed value to 1, and then once we have alerted all of our customers, we can delete those records. This covers us in the unlikely event that all the new stock sells out while we are e-mailing customers, and a new customer completes the notification form.
Read more
  • 0
  • 0
  • 2332
Modal Close icon
Modal Close icon