搜尋
首頁後端開發php教程10 Principles of the PHP Masters

Glen Stansberry on Sep 8th 2008 with 151 comments

Share

4diggsdigg

Discover the industry leader in Email Marketing.Try iContact for FREE today!

With PHP’s widespread adoption,it’s almost too easy to find a script or snippet to do exactly what you need. Unfortunately, there’s no filter as to what is a “good practice” and what’s, well… not so good when writing a PHP script. We need trustworthy sources, who have proven they have a solid grasp on the best practices of PHP.

We need PHP masters to show us the best principles to follow for high-grade PHP programming.

1. Use PHP Only When You Need it ? Rasmus Lerdorf

There’s no better resource than PHP’s creator for knowing what PHP is capable of. Rasmus Lerdorf created PHP in 1995, and since then the language has spread like wildfire through the developer community, changing the face of the Internet. However, Rasmus didn’t create PHP with that intent. PHP was created out of a need to solve web development problems.

And as with many open source projects that have gone on to become popular, the motivation was never philosophical or even narcissistic. It was purely a case of needing a tool to solve real-world Web-related problems. In 1994 the options were fairly limited when it came to Web development tools.

However, you can’t use PHP for everything. Lerdorf is the first to admit that PHP is really just a tool in your toolbox, and that even PHP has limitations.

Use the right tool for the job. I have run across companies that have completely bought into PHP, deploying it absolutely everywhere, but it was never meant to be a general-purpose language appropriate for every problem. It is most at home as the front-end scripting language for the Web.

Trying to use PHP for everything isn’t efficient, and it certainly isn’t the best use of your time as a web developer. Don’t be afraid to to use other languages if PHP isn’t working out for your project.

2. Use Many Tables With PHP and MYSQL for Scalability ? Matt Mullenweg

Nobody needs to question Matt Mullenweg’s authority with PHP. He has, (alongside a rabid community), developed the most popular blogging system on the planet: Wordpress. After creating Wordpress, Matt and company launched the stellar Wordpress.com, a free blogging site based on the Wordpress MU code base blogging software for multiple blogs. At the time of this writing, Wordpress.com hosts over 4 million blogs, and their users have written over 140,000 posts today. (You can see more interesting stats about Wordpress.com usage here.)

If anybody knows how to scale a website, it’s Matt Mullenweg. In 2006 Matt gave some insight into Wordpress’ database structure and explained why Wordpress MU uses a separate MySQL table for each blog, as opposed to using one giant “monolithic” table for all of the blogs.

We tested this approach for MU, but found it was too expensive to scale past a certain point. With monolithic structures you hit a wall based on your hardware. In MU users are divided and can be partitioned easily, for example on WordPress.com we have the users partitioned between 4096 databases, which allows you to scale very cheaply and efficiently to hundreds of thousands and even millions of users and extremely high levels of traffic.

Being able migrate the tables allows the code and ultimately the blogs to run much faster and scale easier. Alongside some heavy caching, and smart database usage, Matt has shown that extremely popular sites like Facebook and Wordpress.com can run off of PHP and handle the incredible traffic load.

3. Never, ever trust your users ? Dave Child

Dave Child is the brainchild (teehee) behind the recently renamed Added Bytes (previously ilovejackdaniels.com) website that featured Dave’s excellent cheat sheets for many programming languages. Dave’s worked for many development companies in the UK and has established himself as an authority in the programming world.

Dave offers some sage advice when it comes to writing secure code in PHP: Don’t trust your users. They just might hurt you.

So the cardinal rule of all web development, and I can’t stress it enough, is: Never, Ever, Trust Your Users. Assume every single piece of data your site collects from a user contains malicious code. Always. That includes data you think you have checked with client-side validation, for example using JavaScript. If you can manage that, you’ll be off to a good start. If PHP security is important to you, this single point is the most important to learn.

Dave goes on to give specific examples of secure practices in parts one, two and three of his ‘Writing Secure PHP’ series. But his ultimate takeaway is this:

Finally, be completely and utterly paranoid.
If you assume your site will never come under attack, or face any problems of any sort, then when something eventually does go wrong, you will be in massive amounts of trouble. If, on the other hand, you assume every single visitor to your site is out to get you and you are permanently at war, you will help yourself to keep your site secure, and be prepared in case things should go wrong.

4. Invest in PHP Caching ? Ben Balbo

Ben Balbo has been writing for Site Point, a very well respected tutorial site for the likes of developers and designers. He’s on the committee for both the Melbourne PHP User Group and Open Source Developers’ Club, so he knows a thing or two about the language. It’s no surprise with Ben’s background as a PHP developer and trainer that he recommends putting a little more thought and preparation into PHP caching.

If you have a busy and predominantly static web site?such as a blog?that’s managed through a content management system, it will likely require little alteration, yet may benefit from huge performance improvements resulting from a small investment of your time. Setting up caching for a more complex site that generates content on a per-user basis, such as a portal or shopping cart system, will prove a little more tricky and time consuming, but the benefits are still clear.

There are many different techniques for caching in PHP, and Ben touches on a few of the bigger ones in the article, like:

cached function calls setting expiry headers caching file downloads in IE template caching Cache_Lite

and many others. Because of the nature of dynamic languages like PHP, caching is critical to store those parts of the page that are accessed frequently and don’t change often.

5. Speed up PHP Development with an IDE, Templates and Snippets ? Chad Kieffer

When Chad Kieffer isn’t busy rocking user interfaces and administering databases, he’s giving expertise advice from his blog 2 tablespoons. Because of Chad’s wide field of expertise, he’s often able to see the big picture that other programmers might not, specifically when it comes to the holistic approach that Chad takes to developing a website. He specializes in all aspects of the development process, so any insights he can provide with putting together an entire project is going to be useful.

Chad believes that using an IDE like Eclipse PDT (Eclipse’s PHP development package) with a mixture of templates and snippets can really speed up the turnaround time on a project.

Busy schedules, long to do lists, and deadlines make it tough for developers to get familiar with some of the advanced features their tools provide. This is a shame, because some features, like Eclipse Templates, can really reduce coding time and errors.

Common sense says that any time you can automate a task, the quicker you’ll get the project done. The same holds true with Dan’s theory. By taking the time to create templates that you’ll use over and over, you’ll save tons of time automating the repetitive parts of coding.

By using an IDE like Eclipse and the PDT package, you’ll find that your development time will incrementally speed up. The IDE will auto-close brackets, add those missing semicolons and even allow you to debug within the editor, without having to upload to the server.
(Chad has a nifty tutorial on getting started with Eclipse PDT and the benefits of an IDE in general, if you’re interested.)

6. Make Better Use of PHP’s Filter Functions ? Joey Sochacki

While Joey Sochacki may not be as big of a name as Matt Mullenweg in the PHP community, he’s a seasoned web developer and shares tips that he’s picked up along the way at his blog Devolio.

Joey has found that even though there is a ton of filtering that has to happen when writing PHP code, not many programmers make use of PHP’s filter functions.

Filtering data. We all have to do it. Most, if not all of us, despise doing it. However, unbeknown to most are PHP’s filter_* functions, that allow us to do all sorts of filtering and validation. Using PHP’s filter_* functions, we can validate and sanitize data types, URLs, e-mail addresses, IP addresses, strip bad characters, and more, all with relative ease.

Filtering can be tricky, but this guide can help immensely. With Joey’s help you’ll learn how to install the filters and and filter nearly anything, taking advantage of the filtering power of PHP.

7. Use a PHP Framework ? Josh Sharp

There has always been a debate as to whether to use a PHP framework like Zend, CakePHP, Code Igniter, or any other framework. There are upsides and downsides to using one, and many developers have their own opinions about whether or not to go down this road.

Josh Sharp is a web developer who makes his bread and butter creating websites for clients. This is why you should trust him when he says it’s a good idea to use a PHP framework to save time and eliminate mistakes when programming. Why? Josh believes it’s because PHP is too easy to learn.

But PHP’s ease of use is also its downfall. Because there are less restrictions on the structure of the code you write, it’s much easier to write bad code. But there is a solution: use a framework.

PHP frameworks help standardize how you program, and can save lots of time in the development process. You can read more about the benefit of using a PHP framework at Josh’s blog.

8. Don’t use a PHP Framework ? Rasmus Lerdorf

Contrary to Josh’s belief that one should use a PHP framework, Rasmus Lerdorf, the Godfather of PHP himself, believes that frameworks aren’t that great. Why? Because they perform much slower than simple PHP.

During Rasmus’ presentation at Drupalcon 2008, Rasmus compared the response times to a PHP page with a simple “Hello World” example, and compared it to a few PHP frameworks (slides 24-32), and showed that PHP frameworks are much slower than straight PHP.

You can listen or watch the entire presentation where Rasmus shows the performance losses with PHP frameworks. In short, Rasmus shows that performance takes a major hit when you use a PHP framework as opposed to using pure PHP.

[Note: If you have to use a PHP framework, Rasmus likes Code Igniter the best, as it is "least like a framework"]

9. Use Batch Processing ? Jack D. Herrington

Jack Herrington is no stranger to PHP and the development world. On top of writing over 30 articles for the prestigious IBM developerWorks, Jack has also published programming books like PHP Hacks. Jack is a bona fide expert.

Herrington recommends using batch processing and cron to tackle those tasks that can process in the background. Web users don’t want to wait long for tasks to complete on the web. There are some jobs that take longer that are much more suited to being done in the background.

Certainly, in some small cases, it’s a bit easier to fire off of a helper thread to handle small jobs. But it’s easy to see that with the use of conventional tools ? cron, MySQL, standard object-oriented PHP, and Pear::DB ? creating batch jobs in PHP applications is easy to do, easy to deploy, and easy to maintain.

Jack believes in simplicity, and instead of using threading on servers, he uses the simple combination of cron, PHP and MySQL to process tasks in the background.

I’ve done both, and I think cron has the advantage of the “Keep It Simple, Stupid” (KISS) principle. It keeps the background processing simple. Instead of having a multithreaded job-processing application that runs forever and, thus, can never leak memory, you have a simple batch script that cron starts. The script determines whether there’s anything to do, does it, then exits. No need to worry about memory leaks. No need to worry about a thread stalling or getting caught in an infinite loop.

10. Turn on Error Reporting Immediately ? David Cummings

David Cummings runs his own software company that specializes in content management systems, and has won several awards. If anyone knows how to develop a PHP application efficiently, it’s Dave.

David wrote in a SitePoint article about the two PHP tips he wished he’d learned in the beginning. One of the tips: Turn on error reporting immediately. It’ll save a great deal of time in the long run.

The single most important thing I tell people who use PHP is to turn error reporting to its maximum level. Why would I want to do this? Generally the error reporting is set at a level that will hide many little things like:

declaring a variable ahead of time, referencing a variable that isn’t available in that segment of code, or using a define that isn’t set.

These factors might not seem like that big a deal ? until you develop structured or object oriented programs with functions and classes. Too often, writing code without error reporting turned up high would cost you hours as you scoured long functions that didn’t work because a variable was misspelled or not accessible.

Error reporting can make finding the reason for an error much easier. A tiny bug in the code can be quickly identified if PHP’s error reporting is turned on high. Save yourself some time and hair pulling by letting PHP find your bugs for you.

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您什麼時候使用特質與PHP中的抽像類或接口?您什麼時候使用特質與PHP中的抽像類或接口?Apr 10, 2025 am 09:39 AM

在PHP中,trait適用於需要方法復用但不適合使用繼承的情況。 1)trait允許在類中復用方法,避免多重繼承複雜性。 2)使用trait時需注意方法衝突,可通過insteadof和as關鍵字解決。 3)應避免過度使用trait,保持其單一職責,以優化性能和提高代碼可維護性。

什麼是依賴性注入容器(DIC),為什麼在PHP中使用一個?什麼是依賴性注入容器(DIC),為什麼在PHP中使用一個?Apr 10, 2025 am 09:38 AM

依賴注入容器(DIC)是一種管理和提供對象依賴關係的工具,用於PHP項目中。 DIC的主要好處包括:1.解耦,使組件獨立,代碼易維護和測試;2.靈活性,易替換或修改依賴關係;3.可測試性,方便注入mock對象進行單元測試。

與常規PHP陣列相比,解釋SPL SplfixedArray及其性能特徵。與常規PHP陣列相比,解釋SPL SplfixedArray及其性能特徵。Apr 10, 2025 am 09:37 AM

SplFixedArray在PHP中是一種固定大小的數組,適用於需要高性能和低內存使用量的場景。 1)它在創建時需指定大小,避免動態調整帶來的開銷。 2)基於C語言數組,直接操作內存,訪問速度快。 3)適合大規模數據處理和內存敏感環境,但需謹慎使用,因其大小固定。

PHP如何安全地上載文件?PHP如何安全地上載文件?Apr 10, 2025 am 09:37 AM

PHP通過$\_FILES變量處理文件上傳,確保安全性的方法包括:1.檢查上傳錯誤,2.驗證文件類型和大小,3.防止文件覆蓋,4.移動文件到永久存儲位置。

什麼是無效的合併操作員(??)和無效分配運算符(?? =)?什麼是無效的合併操作員(??)和無效分配運算符(?? =)?Apr 10, 2025 am 09:33 AM

JavaScript中處理空值可以使用NullCoalescingOperator(??)和NullCoalescingAssignmentOperator(??=)。 1.??返回第一個非null或非undefined的操作數。 2.??=將變量賦值為右操作數的值,但前提是該變量為null或undefined。這些操作符簡化了代碼邏輯,提高了可讀性和性能。

什麼是內容安全策略(CSP)標頭,為什麼重要?什麼是內容安全策略(CSP)標頭,為什麼重要?Apr 09, 2025 am 12:10 AM

CSP重要因為它能防範XSS攻擊和限制資源加載,提升網站安全性。 1.CSP是HTTP響應頭的一部分,通過嚴格策略限制惡意行為。 2.基本用法是只允許從同源加載資源。 3.高級用法可設置更細粒度的策略,如允許特定域名加載腳本和样式。 4.使用Content-Security-Policy-Report-Only頭部可調試和優化CSP策略。

什麼是HTTP請求方法(獲取,發布,放置,刪除等),何時應該使用?什麼是HTTP請求方法(獲取,發布,放置,刪除等),何時應該使用?Apr 09, 2025 am 12:09 AM

HTTP請求方法包括GET、POST、PUT和DELETE,分別用於獲取、提交、更新和刪除資源。 1.GET方法用於獲取資源,適用於讀取操作。 2.POST方法用於提交數據,常用於創建新資源。 3.PUT方法用於更新資源,適用於完整更新。 4.DELETE方法用於刪除資源,適用於刪除操作。

什麼是HTTP,為什麼對Web應用程序至關重要?什麼是HTTP,為什麼對Web應用程序至關重要?Apr 09, 2025 am 12:08 AM

HTTPS是一種在HTTP基礎上增加安全層的協議,主要通過加密數據保護用戶隱私和數據安全。其工作原理包括TLS握手、證書驗證和加密通信。實現HTTPS時需注意證書管理、性能影響和混合內容問題。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。