Home >Backend Development >PHP Tutorial >Developing Robust Code with PHP - An Introduction to Building a Higher Level_PHP Tutorial

Developing Robust Code with PHP - An Introduction to Building a Higher Level_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:29:00752browse

Develop Robust Code with PHP This series of articles is about solving real-world problems in medium to large applications. This series of articles focuses primarily on the new features available in PHP 4, highlighting a host of tips and tricks to make your development life easier. In this series of articles, you'll find many examples and techniques to learn, complete with plenty of sample code. In this first article, PHP guru Amol Hatwar takes a high-level look at how to design and write error-free, maintainable code for medium to large web applications. If you are a developer building web applications and need speed, functionality, and platform-independence, then PHP is for you. And PHP is free, easy to learn and deploy. These are the biggest advantages that make PHP so popular. But these advantages can also turn into disadvantages. Because PHP is so easy to use, developers often shoehorn code into the editor when they should be planning and designing. Moreover, in PHP, there is more than one way to solve a problem, and it is easier to make tragic mistakes that are difficult to correct later. In this series of articles, you'll learn how to avoid many mistakes. If you stick to it one step at a time, don't be surprised if you find yourself writing error-free code in one or two attempts. I'll also point out the new features available in PHP 4 that make development work easier. Most of the examples I'll cover deal with real-world issues such as script configuration and installation, file handling, and database usage. Even if you're new to all this, you'll find it easy to understand. However, I assume you have some basic knowledge of PHP. If you need a refresher, you may find the references listed at the end of this article helpful. (See Resources.) Laying a Strong Foundation Writing code in PHP is very similar to writing code in a language like C. Because they are syntactically similar, they also lead to similar code maintenance issues. When you have to develop a large application, you may have to write a lot of code. Over time, this code can become unmanageable, and bugs can quickly creep in. No matter where you hear this statement, don't believe it—at least not entirely. However, the more important fact is that if you find yourself maintaining code too often, your application is probably poorly designed in the first place. Design your code correctly The choices you make initially will affect the freedom you have when writing code later. This makes correct design an important prerequisite. Although design can become an extra ritual when you solve a trivial problem, you must at least know that this is the way to go. Many people view design and planning as additional overhead. But starting with a bad design, or no design at all, always results in sloppy code. Remember, no amount of clever coding can make up for poor design. Although how to design applications is beyond the scope of this series of articles, I will provide some tips on what to keep in mind when designing web applications. Divide and Conquer It is always preferable to design and write large applications in smaller, loosely coupled parts. This way, every part is maintainable. For example, a Content Management System (CMS) may be distributed across many smaller modules such as user authentication, display, content parsing, and viewing statistics. And, if your module is general enough, you can reuse the code in other applications you develop. Programmers do this all the time, but they still complain. As for coding, the trick is to give each module the functionality it absolutely needs and call it a day. The functions assigned to a module should be just right. Never think about it in the page If you are interested in making your HTML pages more dynamic with PHP, this section is for you. This habit usually starts when you want to display the date and time on every page to make it look up to date. Each HTML page becomes a small PHP script with a limited number of lines, and the date function is hidden somewhere. If this is what you want, you must agree that this is the easiest way to make the job happen. However, imagine what changes you would have to make to change the date format presented on the page. You will have to change the code within each page. Obviously, there are better ways to achieve this. My favorite way is to use a config file and define a constant in the config file that holds the format string for the date() function. You can then use the date() function wherever needed. Each page still ends with a script, but you'll want to minimize the number of changes you have to make to a single line of code. Figure 1. Avoid hard coding As shown in the image above, you can see the date format change on all pages. The idea here is to avoid duplicating code and hard coding. Keep this in mind when writing large applications. Debugging and maintenance become easier when you avoid duplicating code. Reducing client-side requirements The types of Web pages and applications have evolved in many directions.First came images and image mapping, then Java applets and client-side scripts for cool animations. Now comes Flash. Having an impact is good, but you have to remember that the whole idea behind the Web is to make information readily accessible to anyone who needs it. If you use technology that is not supported by all browsers and platforms, you may deny people access to your information. You never know if someone who doesn't have access to your Web site could be your next customer! Your application design should minimize network traffic as much as possible. We often see many websites that get too much traffic and only give the browser a class of cookies that only make it work. Tampering with large numbers of cookies not only consumes bandwidth, but also makes it difficult to manage in many ways. As a rule of thumb, if your application sends more than 40 KB of data or if your page takes more than 5 seconds to load, it's time to design your application from scratch. Small tweaks here and there won't last long. If you look around, you'll see that the most popular, most visited sites are very simple. You should also consider the next wave of mobile devices and the connections they will use to access your application. As a best practice, your application must adapt content based on the client requesting the content. Leon Atkinson says on page 720 of his book Core PHP Programming, "We can try to keep the size of HTML documents small, and we can try to avoid complex HTML such as nested tables. But we can't upgrade everyone's 28.8 modems. " Separate code, content and display HTML is the markup language for displaying content, and PHP is the scripting language embedded in HTML. This really makes simple tasks easy — take dates, for example. However, when you want to implement complex requirements, embedding PHP into HTML takes away from the simplicity of the code. It's good to separate code, content, and display as much as possible. Consider this document you are reading. This document is initially created as an XML file. HTML and PDF versions are automatically generated using stylesheets. The code (the application that shows you the page), the content (the XML document), and the display (the style sheet) are different. Just as it is important to encapsulate core functionality in modules and avoid code duplication, it is also important to have separate source code for content and display the content in the required manner. Your flexibility to customize pages based on client and connection speed is also increased. Also allows programmers, designers, and authors to work independently of each other—a good thing if you're working on a large project. Don't be afraid to throw away the design. No matter what others tell you, practice is the best way to learn application design. If you're just starting out, you're likely to make a lot of mistakes—that's how you learn. Bad design should be discarded. This is why you have to keep code, content, and display loosely coupled — throwing away bad design becomes a means to ease the pain. When you discard stale code and replace it with better code, you preserve content and display. Now, back to what I promised, making your code robust. You must always remember that your code will power other people's content and displays. If your code isn't up to the task, no amount of amazing efforts from other departments can make up for it. Writing Robust Code Assuming that your code requirements remain unchanged, you will not notice the need to change your code. Aside from occasional optimizations and improvements, your code should run like a well-oiled machine. Sound difficult? This is not the case. Frankly, it doesn't take a genius to write robust code. Just ask yourself the right questions when you're in doubt so you don't get sidetracked: Is it safe? Is it simple and easy to understand? Is it platform independent? Is it fast enough? Protect your code Any system that satisfies a large number of users must be secure. Although PHP itself is not vulnerable to black-hat hackers, don't be too sure. PHP 4 prior to version 4.2.2 had a serious security flaw. Always ensure that sensitive data is stored or transmitted over a network with appropriate encryption. This is more important for applications that process business, store information (such as credit card numbers), and transmit confidential data. Nowadays, it is difficult to trust user-submitted data. Make sure the data is verified and that it is clean before use. Remember, by putting your Web application on the Internet, you are exposing your systems, software, data, and business to the vast network. Make sure your code always runs securely. Keep your code simple Your code should be easy to understand, readable, and well documented. To reduce the time it takes to become familiar with your own or other people's code, use common naming and coding conventions throughout your project. Invest the time to ensure that these aspects will pay off when the time comes to maintain your code. It's best to document your code as you program it. There is no tool that can parse all your scripts and create clean-looking HTML-formatted documents for you. If you change the behavior of your code, change the documentation accordingly.It's no use having documentation for your code if it doesn't actually document anything. Make sure your code is documented, simple, and easy to understand. This will help in the long run. Making your code platform-independent Another issue you must address is platform independence. Of course, a script written for PHP on Windows will work for PHP on any other platform: PHP is designed that way. However, you still need to be careful about smaller inconsistencies. For example, the newline character is represented differently in Windows and UNIX. You must also use extraction when accessing resources such as databases located outside PHP. Let’s say your application uses MySQL as the database server to cut costs. If you decide later to have a more feature-rich database, you must change the code in your application. Making significant changes to code is always a chore and an error-prone process. Use decimation to isolate changes to parts that are easily changed. You don't have to rewrite your entire application. Make sure you write platform-independent code. This makes your application more adaptable and scalable. Building for speed The last factor worth dealing with is speed. No one wants to wait while your script shuffles through a selection of about 300 entries from the database and displays a page. It's usually a better idea to put 20 results on 15 different pages that move and load quickly on the user's browser. Users interpret faster response times as speed. Another common mistake is to dynamically create a page every time a user visits it. This does ensure that your site is always up to date, but when the number of users increases, PHP cannot tolerate this. You should cache pages that are used frequently. Caching makes your application faster and reduces the load on the server. Make sure your code

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/531720.htmlTechArticleThe Develop Robust Code with PHP series of articles is about solving practical problems in large and medium-sized applications. This series of articles focuses primarily on the new features available in PHP 4, highlighting the big...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn