How E-Commerce Site

E-Commerce Site
Dr.NaveenBansal Profile Pic
Published Date:25-10-2017
Your Website URL(Optional)
8644ch01.qxd 1/30/08 12:02 PM Page 3 CHAPTER 1 ■ ■ ■ Starting an E-Commerce Site T he word “e-commerce” has had a remarkable fall from grace in the past few years. Just the idea of having an e-commerce web site was once enough to get many businesspeople salivating in anticipation. But now, it’s no longer enough to say, “E-commerce is the future—get online or get out of business.” You now need compelling, realistic, and specific reasons to take your business online. If you want to build an e-commerce site today, you must answer some tough questions. Here are a few things to ask yourself: • Many big e-commerce sites have failed. What can e-commerce possibly offer me in today’s tougher environment? • Most e-commerce companies seem to need massive investment. How can I produce a site on my limited budget? • Even successful e-commerce sites expect to take years before they turn a profit. My business can’t wait that long. How can I make money now? We’ll take a shot at answering these questions in this chapter. Deciding Whether to Go Online Although there are hundreds of possible reasons to go online, they tend to fall into the following groups: • Retain existing customers and get new customers • Encourage existing customers to spend more money • Reduce the costs of fulfilling orders We’ll look at each of these in the following sections. Get More Customers Getting more customers is immediately the most attractive reason to go online. With an e-commerce site, even small businesses can reach customers all over the world. This reason can also be the most dangerous, however, because many people set up e-commerce sites assuming that the site will reach customers immediately. It won’t. In the offline world, you 3 1/30/08 12:02 PM Page 4 4 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE need to know a shop exists before you can go into it. This is still true in the world of e-commerce— people must know your site exists before you can hope to get a single order. Addressing this issue is largely a question of making your site known. Aside from advertis- ing, methods of getting more customers to visit include registering the web site with the popular search engines and directory listings, optimizing the site for search-engine ranking, creating forums, sending newsletters, and so on. In this book, we don’t cover the aspects of selling your site; we focus on ways to sell the products listed on your site. But this book does include some basic search engine optimiza- tion techniques (to attract visitors), and it provides a well-designed presentation that will sell the site once your customers visit it. Encourage Customers to Spend More Assuming your company already has customers, you probably wish that they bought more. What stops them? If the customers don’t want any more of a certain product, there’s not a lot that e-commerce can do, but there are other roadblocks on the sales path that can be removed, such as these: • Getting to the physical location of the shop or placing an order by mail is a hassle. • Some of the things you sell can be bought from more convenient places. • You’re mostly open while your customers are at work. • It’s harder to implement an efficient product recommendation system in a physical store. A quality e-commerce site can increase your business revenue. The convenience of being online also means that people are more likely to choose you over other local suppliers. Because your site is online 24 hours a day, rather than the usual 9 to 5, your customers can shop with you outside of their working hours. Having an online store brings a double blessing to you if your customers work in offices, because they can indulge in retail therapy directly from their desks. People with Internet access will find placing an order online far easier than any other method—meaning that when the temptation to buy strikes, it’s much easier for them to give in. Skillful e-commerce design can encourage your customers to buy things they wouldn’t usu- ally think of. Special offers to regular shoppers, suggested impulse purchases before or during checkout, useful accessories presented alongside the main product, and showing a more expen- sive alternative to the one they’re considering encourage customers to buy more. You can easily update your site to suggest items of particular seasonal interest, to announce interesting new products, or to recommend products similar to what a specific customer has already bought. You’ll learn how to use some of these methods in later chapters; by the end of this book, you’ll have a good idea of how to add more features for yourself. Finally, it’s much easier to learn about your customers via e-commerce than in face-to-face shops or even with mail order. Even if you just gather e-mail addresses, you can use these to send out updates and news. More sophisticated sites can automatically analyze a customer’s buying habits to make suggestions on other products the customer might like to buy. Another related benefit of e-commerce is that there’s no real cost in having people browse without buying. In fact, getting people to visit the site as often as possible can be valuable. You should consider building features into the site that are designed purely to make people visit 1/30/08 12:02 PM Page 5 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE 5 regularly; for example, you might include community features such as forums or free content related to the products you’re selling. Reduce the Costs of Fulfilling Orders A well-built e-commerce site will be much less expensive to run than a comparable offline business. Under conventional business models, a staff member must feed an order into the company’s order-processing system. With e-commerce, the customer can do this for you—the gateway between the site and the order processing can be seamless. Of course, after your e-commerce site is up and running, the cost of actually taking orders gets close to zero—you don’t need to pay for checkout staff, assistants, security guards, or rent in a busy shopping mall. If you have a sound business idea, and you execute the site well, you can receive these bene- fits without a massive investment. What’s important is to always focus on the almighty dollar: Will your site, or any particular feature of it, really help you get more customers, retain existing customers, and get customers to spend more, or will it reduce costs and therefore increase your margins? Now it’s time to introduce the site we’ll be using as the example in this book and see just how all of these principles relate to our own shop. Let’s Make Money We’re going to build an e-commerce store that sells t-shirts. On e-commerce sites, there’s always a trade-off to make between building an amazing site that everybody will love and creating a site on a limited budget that will make money. Usually, I’m on the all-the-bells-and-whistles-really- amazing-site side, but I’m always grateful that my ambitions are reined in by the actual business demands. If you’re designing and building the site for yourself and you are the client, then you have a challenge—keeping your view realistic while maintaining your enthusiasm for the project. This book shows you a logical way to build an e-commerce site that will deliver what it needs to be profitable. However, when designing your own site, you need to think carefully about exactly who your customers are, what they need, how they want to place orders, and what they are most likely to buy. Consider the following points before you start to visualize or design the site and certainly before you start programming: Getting customers: How will you get visitors to the site in the first place? Offering products: What will you offer, and how will you expect customers to buy? Will they buy in bulk? Will they make a lot of repeat orders? Will they know what they want before they visit, or will they want to be inspired? These factors will influence how you arrange your catalog and searching as well as what order process you use. A shopping basket is great if people want to browse. If people know exactly what they want, then they might prefer something more like an order form. Processing orders: How will you turn a customer order into a parcel ready for mailing? Your main consideration here is finding an efficient way to process payments and deliver orders to whoever manages your stocks or warehouse. How will you give your customers confi- dence in your ability to protect their data and deliver their purchases on time? 1/30/08 12:02 PM Page 6 6 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE Serving customers: Will customers require additional help with products that they buy from you? Do you need to offer warranties, service contracts, or other support services? Bringing customers back: How will you entice customers back to the site? Are they likely to only visit the site to make a purchase, or will there be e-window-shoppers? Are your prod- ucts consumables, and can you predict when your customers will need something new? After you’ve answered these questions, you can start designing your site, knowing that you’re designing for your customers—not just doing what seems like a good idea at the time. The example site presented in this book has taken a deliberate generic approach to show you the most common e-commerce techniques. To really lift yourself above the competition, however, you don’t need fancy features or Flash movies—you just need to understand, attract, and serve your customers better than anybody else. This book will help you do that. Risks and Threats All this might make it sound as if your e-commerce business can’t possibly fail. Well, it’s time to take a cold shower and realize that even the best-laid plans often go wrong. Some risks are particularly relevant to e-commerce companies, such as • Hacking • Credit card scams • Hardware failures • Unreliable shipping services • Software errors • Changing laws You can’t get rid of these risks, but if you know about them, you can defend your site from them. An important way to protect your site from many risks is to maintain backups. You already know backups are important. But if you’re anything like us, when it gets to the end of the day, saving five minutes and going home earlier seems even more important. When you have a live web site, this simply isn’t an option. Two words: Back up (your web site). Every day. We don’t talk much about the legal side of e-commerce in this book because we are pro- grammers, not lawyers. However, if you are setting up an e-commerce site that goes much beyond an online garage sale, you’ll need to look into these issues before putting your busi- ness online. While we’re on the subject of risks and threats, one issue that can substantially damage your e-commerce site’s reputation is unreliable order fulfillment. This book shows you how to construct a web site that offers products, takes customer orders, and communicates those orders to the owner. An essential part of the process is delivering the products, and to do this, you need a good logistics network set up before launching your shop. If your store doesn’t deliver the goods, customers won’t come back or refer their friends. 1/30/08 12:02 PM Page 7 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE 7 ■ Tip Webmonkey provides an excellent general e-commerce tutorial, which covers taxation, shipping, and many of the issues you’ll face when designing your site, at e-business/building/tutorials/tutorial3.html. Check this out before you start designing your site. Designing for Business Building an e-commerce site requires a significant investment. If you design the site in phases, you can reduce the initial investment and therefore cut your losses if the idea proves unsuccess- ful. You can use the results from an early phase to assess whether it’s worthwhile to add extra features and even use revenue from the site to fund future development. If nothing else, planning to build the site in phases means that you can get your site online and receiving orders much earlier than if you build every possible feature into the first release. Even after you’ve completed your initial planned phases, things generally do not end there. When planning a large software project, it’s important to design in a way that makes inevitable future growth easy. In Chapter 2, where we’ll start dealing with the technical details of building e-commerce sites, you’ll learn how to design the web site architecture to allow for long-term development flexibility. If you’re building sites for clients, they will like to keep their options open. Planning the site, or any other software, in phases will help your clients feel comfortable doing business with you. They will be able to see that you are getting the job done and can decide to end the project at the end of any phase if they feel—for whatever reason—that they don’t want to con- tinue to invest in development. Phase I: Getting a Site Up Chapters 2 through 11 concentrate on establishing the basic framework for the site and putting a product catalog online. We’ll start by putting together the basic site architecture and deciding how the different parts of the application will work together. We’ll then build the product cata- log into this architecture. You’ll learn how to • Design a database for storing a product catalog containing departments, categories, and products • Write the Structured Query Language (SQL) and Hypertext Preprocessor (PHP) code for accessing that data and making the product catalog functional • Add data to the product catalog that defines product attributes, such as color and size • Provide a product search engine • Implement basic techniques to make your web site search engine friendly and reduce URL link and redirect errors • Receive payments through PayPal Website Payments Standard • Give the site’s administrators a private section of the site where they can administer the catalog online 1/30/08 12:02 PM Page 8 8 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE After you’ve built this catalog, you’ll see how to offer the products for sale by integrating it with PayPal’s shopping cart and order-processing system, which will handle credit card trans- actions for you and e-mail you with details of orders. These orders will be processed manually, but in the early stages of an e-commerce site, the time you lose processing orders will be less than the time it would have taken to develop an automated system. Phase II: Creating Your Own Shopping Cart Using PayPal’s shopping cart is OK and very easy, but it does mean you miss out on a lot of advantages. For example, you can’t control the look and feel of PayPal’s shopping cart, whereas if you use your own, you can make it an integral part of the site. This is a significant advantage, but it’s superficial compared to some of the others. For example, with your own shopping cart, you can store complete orders in the database as part of the order process and use that data to learn about the customers. With additional work, you also can use the shopping basket and checkout process as a platform for selling more prod- ucts. How often have you been tempted by impulse purchases near the checkout of your local store? Well, impulse shopping also works with e-commerce. Having your own shopping cart and checkout gives you the option of offering low-cost special offers from the shopping cart at checkout. You can even analyze the contents of the cart and make suggestions based on this. Chapters 12 through 15 show you how to • Build your own shopping cart • Pass a complete order through to PayPal for credit card processing • Add AJAX features to your product catalog and shopping cart to enhance the user experience • Create an order administration page • Implement a product recommendation system Once again, at the end of Phase II, our site will be fully operational. You can leave it as it is or add features within the existing PayPal-based payment system. But when the site gets seri- ous, you’ll want to start processing orders and credit cards yourself. This is the part where things get complicated, and you need to be serious and careful about your site’s security. Phase III: Processing Orders and Adding Features The core of e-commerce—and the bit that really separates it from other web-development projects—is handling orders and credit cards. PayPal has helped us put this off, but there are many good reasons why—eventually—you’ll want to part company with PayPal: Cost: PayPal is not expensive, but the extra services it offers must be paid for somehow. Mov- ing to a simpler credit card processing service can mean lower transaction costs (this is not a rule though), although developing your own system will obviously incur upfront costs. 1/30/08 12:02 PM Page 9 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE 9 Freedom: PayPal has a fairly strict set of terms and conditions and is designed for resi- dents of a limited number of countries. By taking on more of the credit card processing responsibility yourself, you can better control the way your site works. As an obvious example, you can accept payment using regional methods such as the Switch debit cards common in the United Kingdom. Integration: If you deal with transactions and orders using your own system, you can integrate your store and your warehouse to whatever extent you require. You could even automatically contact a third-party supplier and have the supplier ship the goods straight to the customer. Information: When you handle the whole order yourself, you can record and collate all the information involved in the transaction—and then use it for marketing and research purposes. By integrating the order processing with the warehouse, fulfillment center, or suppliers, you can reduce costs significantly. This might reduce the need for staff in the fulfillment center or allow the business to grow without requiring additional staff. Acquiring information about customers can feed back into the whole process, giving you valuable information about how to sell more. For example, using that data, you could e-mail customers with special offers or just keep in touch with a newsletter. You also could analyze buying patterns and use that data to formulate targeted marketing campaigns. During Phase III, which is covered in Chapters 16 through 22, you will learn how to • Build a customer accounts module so that customers can log in and retrieve their details every time they make an order • Allow customers to add product reviews • Integrate products into your web site using XML Web Services • Establish secure connections using Secure Socket Layer (SSL) so that data sent by users is encrypted on its travels across the Internet • Charge credit cards using DataCash,, and PayPal Website Payments Pro (formerly known as VeriSign Payflow Pro) • Store credit card numbers securely in a database This third phase is the most involved and requires some hard and careful work. By the end of Phase III, however, you will have an e-commerce site with a searchable product catalog, shopping cart, secure checkout, and complete order-processing system. 1/30/08 12:02 PM Page 10 10 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE TShirtShop As we said earlier, we’re going to build an online shop called TShirtShop (which will sell, sur- prisingly enough, t-shirts). Figure 1-1 shows how TShirtShop will look at some point during the second stage of development. Figure 1-1. TShirtShop during Phase II of development ■ Tip You can find a link to an online version of TShirtShop at mysql-ecommerce-2/. Many thanks go to the folks at Going Postal ( who allowed us to use some of their products to populate our virtual TShirtShop store. For the purposes of this book, we’ll assume that the client already exists as a mail-order company and has a good network of customers. The company is not completely new to the business and wants the site to make it easier and more enjoyable for its existing customers to buy—with the goal that customers will end up buying more. 1/30/08 12:02 PM Page 11 CHAPTER 1 ■ STARTING AN E-COMMERCE SITE 11 Knowing this, we suggest the building and opening the TShirtShop web site in phases for the following reasons: • The company is unlikely to get massive orders initially—we should keep the initial cost of building the web site down as much as possible. • The company is accustomed to manually processing mail orders, so manually process- ing orders e-mailed by PayPal will not introduce many new problems. • The company doesn’t want to invest all of its money in a massive e-commerce site only to find that people actually prefer mail order after all Or it might find that, after Phase I, the site does exactly what it wants, and there’s no point in expanding it further. Either way, we hope that offering a lower initial cost gives our bid the edge (it might also mean we can get away with a higher total price). Because this company is already a mail-order business, it probably already has a merchant account and can process credit cards. Therefore, moving on to Phase III as soon as possible would be best for this company, so it can benefit from the preferential card-processing rates. Summary In this chapter, we’ve discussed the positive financial and customer service aspects of including e-commerce in your business operation. In the real and sometimes hostile commercial world, where it’s important to focus on raising short-term revenue and minimizing risk, an e-commerce site will help you by • Increasing your customer base • Persuading your customers to spend more • Lowering your fulfillment costs We’ve applied those principles to a three-phase plan that provides a deliverable, usable site at each stage and continues to expand throughout this book. At this point, you’ve presented your plan to the owners of the t-shirt shop. In the next chap- ter, you’ll put on your programming hat and start to design and build the web site (assuming you got the contract, of course). 1/30/08 12:02 PM Page 12 1/30/08 12:03 PM Page 13 CHAPTER 2 ■ ■ ■ Laying Out the Foundations Now that you’ve convinced the client that you can create a cool web site to complement his or her activity, it’s time to stop celebrating and start thinking about how to put into practice all the promises you’ve made. As usual, when you lay down on paper the technical requirements you must meet, everything starts to seem a bit more complicated than initially anticipated. To ensure this project’s success, you need to come up with a smart way to implement what you agreed to when you signed the contract. You want to develop the project smoothly and quickly, but the ultimate goal is to make sure the client is satisfied with your work. Conse- quently, you should aim to provide your site’s increasing number of visitors with a positive web experience by creating a pleasant, functional, and responsive web site. The requirements are high, but this is normal for an e-commerce site today. To maximize the chances of success, we’ll analyze and anticipate as many of the technical requirements as possible and implement solutions in a way that supports changes and additions with minimal effort. Your goals for this chapter are to • Analyze the project from a technical point of view • Analyze and choose the architecture for your application • Decide which technologies, programming languages, and tools to use • Consider naming and coding conventions ■Note Be warned that this and the next few chapters are dense, and you may find them pretty challenging if you don’t have much experience with PHP or MySQL. Books such as Beginning PHP and MySQL 5: From Novice to Professional,Second Edition (W. Jason Gilmore. Apress, 2006.) do a good job of preparing you to build your first e-commerce web site. Also, we strongly recommend that you consistently follow an efficient project management methodology to maximize the chances of the project’s success, on budget and on time. Most project management theories imply that you and your client have signed an initial requirements/specifications document containing the details of the project you’re about to create. You can use this document as a guide while creating the solution; it also allows you to charge extra if the client brings new requirements or requests changes after development has started. 13 1/30/08 12:03 PM Page 14 14 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS Designing for Growth The word “design” in the context of a web application can mean many things. Its most popular usage probably refers to the visual and user interface design of a web site. This aspect is crucial because, let’s face it, the visitor is often more impressed with how a site looks and how easy it is to use than about which technologies and techniques are used behind the scenes or what operating system the web server is running. If the site is slow, hard to use, or easy to forget, it just doesn’t matter what rocket science was used to create it. Unfortunately, this truth makes many inexperienced programmers underestimate the importance of the way the invisible part of the site is implemented—the code, the database, and so on. The visual part of a site gets visitors interested to begin with, but its functionality makes them come back. A web site can sometimes be implemented very quickly based on certain initial requirements, but if not properly architected, it can become difficult, if not impossible, to change. For any project of any size, some preparation must be done before starting to code. Still, no matter how much preparation and design work is done, the unexpected does happen, and hidden catches, new requirements, and changing rules always seem to work against dead- lines. Even without these unexpected factors, site designers are often asked to change or add functionality many times after the project is finished and deployed. This will also be the case for TShirtShop, which will be implemented in three separate stages, as discussed in Chapter 1. You will learn how to create the web site so that the site (or you) will not fall apart when functionality is extended or updates are made. Because this is a programming book, instead of focusing on how to design the user interface or on marketing techniques, we’ll pay close attention to designing the code that makes them work. The phrase “designing the code” can have different meanings; for example, we’ll need to have a short talk about naming conventions. Yet, the most important aspect that we need to take a look at is the application architecture. The architecture refers to the way you split the code into smaller components (for example, the product search feature) for a simple piece of functionality. Although it might be easier to implement that functionality as quickly and as simply as possible in a single component, you gain great long-term advantages by creating smaller, more simple components that work together to achieve the desired result. Before talking about the architecture itself, you must determine what you want from this architecture. Meeting Long-Term Requirements with Minimal Effort Apart from the fact that you want a fast web site, each of the phases of development we talked about in Chapter 1 brings new requirements that must be met. Every time you proceed to a new stage, you want to be able to reuse most of the already existing solution. It would be very inefficient to redesign the whole site (not just the visual part but the code as well) just because you need to add a new feature. You can make it easier to reuse a solution by planning ahead, so any new functionality that needs to be added can be plugged in with ease, rather than each change causing a new headache. When building the web site, implementing a flexible architecture composed of pluggable components allows you to add new features—such as the shopping cart, the departments list, or the product search feature—by coding them as separate components and plugging them into the existing application. Achieving a good level of flexibility is one of the main goals regard- ing the application’s architecture, and this chapter shows how you can put this into practice. 1/30/08 12:03 PM Page 15 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS 15 You’ll see that the flexibility level is proportional to the amount of time required to design and implement it, so we’ll try to find a compromise that will provide the best gains without com- plicating the code too much. Another major requirement that is common to all online applications is having a scalable architecture. Scalability is defined as the capability to increase resources to yield a linear increase in service capacity. In other words, ideally, in a scalable system, the ratio (proportion) between the number of client requests and the hardware resources required to handle those requests is constant, even when the number of clients increases. An unscalable system can’t deal with an increasing number of clients, no matter how many hardware resources are provided. Because we’re optimistic about the number of customers, we must be sure that the site will be capable of delivering its functionality to a large number of clients without throwing out errors or per- forming sluggishly. Reliability is also a critical aspect for an e-commerce application. With the help of a coher- ent error-handling strategy and a powerful relational database, you can ensure data integrity and ensure that noncritical errors are properly handled without bringing the site to its knees. The Magic of the Three-Tier Architecture Generally, the architecture refers to the way we split the code that implements a feature of the application into separate components based on what they do and grouping each kind of com- ponent into a single logical tier. In particular, the three-tier architecture refers to an architecture that is based on these tiers: • The presentation tier • The business tier • The data tier The presentation tier contains the user interface elements of the site and includes all the logic that manages the interaction between the visitor and the client’s business. This tier makes the whole site feel alive, and the way you design it has a crucial importance for the site’s success. Because your application is a web site, its presentation tier is composed of dynamic web pages. The business tier (also called the middle tier) receives requests from the presentation tier and returns a result to the presentation tier depending on the business logic it contains. Almost any event that happens in the presentation tier usually results in the business tier being called (utilized), except events that can be handled locally by the presentation tier, such as simple input data validation, and so on. For example, if the visitor is doing a product search, the pres- entation tier calls the business tier and says, “Please send me back the products that match this search criterion.” Most of the time, the business tier needs to call the data tier for informa- tion to be able to respond to the presentation tier’s request. The data tier (sometimes referred to as the database tier) is responsible for managing the application’s data and sending it to the business tier when requested. For the TShirtShop e-commerce site, you’ll need to store data about products (including their categories and their departments), users, shopping carts, and so on. Almost every client request finally results in the data tier being interrogated for information (except when previously retrieved data has been cached at the business tier or presentation tier levels), so it’s important to have a fast 1/30/08 12:03 PM Page 16 16 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS database system. In Chapters 4 and 5, you’ll learn how to design the database for optimum performance. These tiers are purely logical—there is no constraint on the physical location of each tier. In theory, you are free to place all of the application, and implicitly all of its tiers, on a single server machine, or you can place each tier on a separate machine if the application permits this. Chapter 22 explains how to integrate functionality from other web sites using XML Web Services. XML Web Services permit easy integration of functionality across multiple servers without the hassle of customized code. An important constraint in the three-tier architecture model is that information must flow in sequential order among tiers. The presentation tier is only allowed to access the business tier, and it can never directly access the data tier. The business tier is the brain in the middle that communicates with the other tiers and processes and coordinates all the information flow. If the presentation tier directly accessed the data tier, the rules of three-tier architecture pro- gramming would be broken. These rules may look like limitations at first, but when utilizing an architecture, you need to be consistent and obey its rules to reap the benefits. Sticking to the three-tier architecture ensures that your site remains easily updated or changed and adds a level of control over who or what can access your data. This may seem to be unnecessary overhead for you right now; however, there is a substantial future benefit of adhering to this system whenever you need to change your site’s functioning or logic. Figure 2-1 is a simple representation of the way data is passed in an application that implements the three-tier architecture. Figure 2-1. Simple representation of the three-tier architecture A Simple Example Using the Three-Tier Architecture It’s easier to understand how data is passed and transformed between tiers if you take a closer look at a simple example. To make the example even more relevant to our project, let’s analyze a situation that will actually happen in TShirtShop. This scenario is typical for three-tier appli- cations. Like most e-commerce sites, TShirtShop will have a shopping cart, which we will discuss later in the book. For now, it’s enough to know that the visitor will add products to the shop- ping cart by clicking an Add to Cart button. Figure 2-2 shows how the information flows through the application when that button is clicked. 1/30/08 12:03 PM Page 17 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS 17 At step 1, the user clicks the Add to Cart button for a specific product. At step 2, the presenta- tion tier (which contains the button) forwards the request to the business tier, “Hey, I want this product added to my shopping cart” At step 3, the business tier receives the request, understands that the user wants a specific product added to the shopping cart, and handles the request by telling the data tier to update the visitor’s shopping cart by adding the selected product. The data tier needs to be called, because it stores and manages the entire web site’s data, including users’ shopping cart information. At step 4, the data tier updates the database and eventually returns a success code to the business tier. At step 5, the business tier handles the return code and any errors that might have occurred in the data tier while updating the database and then returns the output to the presentation tier. Figure 2-2. Internet visitor interacting with a three-tier application At step 6, the presentation tier generates an updated view of the shopping cart. At step 7, the results of the execution are wrapped up by generating a Hypertext Markup Language (HTML) web page that is returned to the visitor where the updated shopping cart can be seen in the visitor’s web browser. Note that, in this simple example, the business tier doesn’t do a lot of processing, and its business logic isn’t very complex. However, if new business rules appear for your application, you would change the business tier. If, for example, the business logic specified that a product could be added to the shopping cart only if its quantity in stock was greater than zero, an addi- tional data tier call would have been made to determine the quantity. The data tier would be requested to update the shopping cart only if products are in stock. In any case, the presenta- tion tier is informed about the status and provides human-readable feedback to the visitor. 1/30/08 12:03 PM Page 18 18 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS What’s in a Number? It’s interesting to note how each tier interprets the same piece of information differently. For the data tier, the numbers and information it stores have no significance because this tier is an engine that saves, manages, and retrieves numbers, strings, or other data types—to the data tier this data is just arbitrary information, not product quantities or product names. In the context of the previous example, a product quantity of zero represents a simple, plain number without any meaning to the data tier (it is simply zero, a 32-bit integer). The data only gains significance when the business tier reads it. When the business tier asks the data tier for a product quantity and gets a “0” result, this is interpreted by the business tier as, “Hey, no products in stock” This data is finally wrapped in a nice, visual form by the presen- tation tier, such as a label reading, “Sorry, at the moment this product cannot be ordered.” Even if it’s unlikely that you want to forbid a customer from adding a product to the shop- ping cart if the product is not in stock, the example (described in Figure 2-3) is good enough to present in yet another way how each of the three tiers has a different purpose. Figure 2-3. Example of information exchange among application tiers The Right Logic for the Right Tier Because each layer contains its own logic, sometimes it can be tricky to decide where exactly to draw the lines between tiers. In the previous scenario, instead of reading the product’s quantity in the business tier and deciding whether the product is available based on that number (resulting ultimately in two database calls), you could have a single stored procedure named add_product_if_available that adds the product to the shopping cart only if it’s avail- able in stock. In this scenario, some logic is transferred from the business tier to the data tier. In many other circumstances, you might have the option to place some logic in one tier or another or 1/30/08 12:03 PM Page 19 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS 19 maybe in both. In most cases, there is no single best way to implement the three-tier architec- ture, and you’ll need to make a compromise or a choice based on personal preference or external constraints. Furthermore, there are occasions in which even though you know the right way (in respect to the architecture) to implement something, you might choose to break the rules to get a per- formance gain. As a general rule, if performance can be improved this way, it is OK to break the strict limits between tiers just a little bit (for example, add some of the business rules to the data tier or vice versa), if these rules are not likely to change in time. Otherwise, keeping all the business rules in the middle tier is preferable, because it generates a cleaner application that is easier to maintain. Finally, don’t be tempted to access the data tier directly from the presentation tier. This is a common mistake that is the shortest path to a complicated, hard-to-maintain, and inflexible system. In many data access tutorials or introductory materials, you’ll be shown how to perform basic database operations using a simple user interface application. In these kinds of programs, all the logic is probably written in a short, single file, instead of separate tiers. Although the materials might be very good, keep in mind that most of these texts are meant to teach you how to do different individual tasks (for example, access a database), and not how to correctly create a flexible and scalable application. A Three-Tier Architecture for TShirtShop Implementing a three-tier architecture for the TShirtShop web site will help achieve the goals listed at the beginning of the chapter. The coding discipline, imposed by a system that might seem rigid at first sight, allows for excellent levels of flexibility and extensibility in the long run. Splitting major parts of the application into separate smaller components encourages reusability. More than once when adding new features to the site, you’ll see that you can reuse some of the already existing bits. Adding a new feature without needing to change much of what already exists is, in itself, a good example of reusability. Another advantage of the three-tiered architecture is that, if properly implemented, the overall system is resistant to changes. When bits in one of the tiers change, the other tiers usu- ally remain unaffected, sometimes even in extreme cases. For example, if for some reason the back-end database system is changed (say, the manager decides to use PostgreSQL instead of MySQL), you only need to update the data tier and maybe just a little bit of the business tier. Why Not Use More Tiers? The three-tier architecture we’ve been talking about so far is a particular (and the most popular) version of the n-tier architecture. n-tier architecture refers to splitting the solution into a num- ber (n) of logical tiers. In complex projects, sometimes it makes sense to split the business layer into more than one layer, thus resulting in architecture with more than three layers. However, for our web site, it makes the most sense to stick with the three-layered design, which offers most of the benefits while not requiring too many hours of design or a complex hierarchy of framework code to support the architecture. Maybe with a more involved and complex architecture, you could achieve even higher levels of flexibility and scalability for the application, but you would need much more time for design before starting to implement anything. As with any programming project, you must find a fair balance between the time required to design the architecture and the time spent to implement it. The three-tier architecture is best suited to projects with average complexity, such as the TShirtShop web site. 1/30/08 12:03 PM Page 20 20 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS You also might be asking the opposite question, “Why not use fewer tiers?” A two-tier architecture, also called client-server architecture, can be appropriate for less complex projects. In short, a two-tier architecture requires less time for planning and allows quicker development in the beginning; however, it generates an application that’s harder to maintain and extend in the long run. Because we’re expecting to have to extend the application in the future, the client- server architecture is not appropriate for our application, so it won’t be discussed further in this book. Now that the general architecture is known, let’s see what technologies and tools you will use to implement it. We’ll have a brief discussion of the technologies, and in Chapter 3, you’ll create the foundation of the presentation and data tiers by creating the first page of the site and the back-end database. You’ll start implementing real functionality in each of the three tiers in Chapter 4 when you start creating the web site’s product catalog. Choosing Technologies and Tools No matter which architecture is chosen, a major question that arises in every development project is which technologies, programming languages, and tools are going to be used, bear- ing in mind that external requirements can seriously limit your options. In this book, we’re creating a web site using PHP 5, MySQL 5, and related technologies. We really like these technologies, but it doesn’t necessarily mean they’re the best choice for any kind of project, in any circumstances. Additionally, there are many situations in which you must use specific technologies because of client requirements. The Requirements Analysis stage that is present in most software development process will determine which technolo- gies you must use for creating the application. Although the book assumes some previous experience with PHP and MySQL, we’ll take a quick look at them and see how they fit into our project and into the three-tier architecture. Using PHP to Generate Dynamic Web Content PHP is an open source technology for building dynamic, interactive web content. Its short description (on the official PHP web site, is “PHP is a widely-used general-purpose scripting language that is especially suited for web development and can be embedded into HTML.” PHP stands for PHP: Hypertext Preprocessor (yes, it’s a recursive acronym) and is avail- able for free download at its official web site. The story of PHP, having its roots somewhere in 1994, is a successful one. Among the factors that led to its success are the following: • PHP is free; especially when combined with Linux server software, PHP can prove to be a very cost-efficient technology to build dynamic web content. • PHP has a shorter learning curve than other scripting languages. • The PHP community is agile. Many useful helper libraries or new versions of the exist- ing libraries are being developed (such as those you can find in the PEAR repository or at, and new features are added frequently. • PHP works very well on a variety of web servers and operating systems (Unix-like plat- forms, Windows, and Mac OS). 1/30/08 12:03 PM Page 21 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS 21 However, PHP is not the only server-side scripting language around for creating dynamic web pages. Among its most popular competitors are JavaServer Pages (JSP), Perl, ColdFusion, and ASP.NET. Among these technologies are many differences but also some fundamental similarities. For example, pages written with any of these technologies are composed of basic HTML, which draws the static part of the page (the template), and code that generates the dynamic part. ■Note You might want to check out Beginning ASP.NET 2.0 E-Commerce in C 2005 (Cristian Darie and Karli Watson. Apress, 2005.), which explains how to build e-commerce web sites with ASP.NET 2.0, C, and SQL Server 2005. Using Smarty to Separate Layout from Code Because PHP is simple and easy to start with, it has always been tempting to start coding with- out properly designing an architecture and framework that would be beneficial in the long run. What makes things even worse is that the straightforward method of building PHP pages is to mix PHP instructions with HTML because PHP doesn’t have, by default, an obvious tech- nique of separating the PHP code from the HTML layout information. Mixing the PHP logic with HTML has two important disadvantages: • This technique often leads to long, complicated, and hard-to-manage code. Maybe you have seen those kilometric source files with an unpleasant mixture of PHP and HTML, which are hard to read and impossible to understand after a week. • These mixed files are the subject of both designers’ and programmers’ work, which complicates the collaboration more than necessary. This also increases the chances of the designer creating bugs in the code logic while working on cosmetic changes. These kinds of problems led to the development of template engines, which offer frameworks separating the presentation logic from the static HTML layout. Smarty ( is the most popular and powerful template engine for PHP . Its main purpose is to offer you a simple way to separate application logic (PHP code) from its presentation code (HTML). This separation permits the programmer and the template designer to work independ- ently on the same application. The programmer can change the PHP logic without needing to change the template files, and the designer can change the templates without caring how the code that makes them alive works. Figure 2-4 shows the relationship between the Smarty design template file and its Smarty plug-in file. 1/30/08 12:03 PM Page 22 22 CHAPTER 2 ■ LAYING OUT THE FOUNDATIONS Figure 2-4. Smarty componentized template The Smarty design template (a .tpl file containing the HTML layout and Smarty-specific tags and code) and its Smarty plug-in file (a .php file containing the associated code for the template) form a Smarty componentized template. In practice, we’ll not create a Smarty plug-in file for each template, as shown in Figure 2-4. Instead, we’ll create a generic Smarty plug-in that integrates with all your Smarty templates, loading the necessary presentation objects. Presentation objects are classes that provide the template files with the data they need. You’ll learn more about how Smarty works while you’re building the e-commerce web site. For a concise introduction to Smarty, read the Smarty Crash Course at crashcourse.php. For a detailed reference, we recommend Smarty PHP Template Programming and Applications (Hasin Hayder, J. P. Maia, and Lucian Gheorghe. Packt Publishing, 2006.). ■Note Adding Smarty or another templating engine to a web application’s architecture adds some initial coding effort and also implies a learning curve. However, you should try it anyway, because the advantages of using such a modern development technique will prove to be significant later in the process. What About the Alternatives? Smarty is not the only template engine available for PHP. You can find many others by Googling for “PHP template engines.” You can find the most popular of them nicely listed by Justin Silverton in his article “Top 25 PHP Template Engines” (your favorite search engine will help you, once again, find the article). Although all template engines follow the same basic principles, we chose to use Smarty in the PHP e-commerce project for this book because of its very good performance results, power- ful features (such as template compilation and caching), and wide acceptance in the industry.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.