Advanced PHP Programming
Many of the previous generation of PHP books were fattened with lots of filler: how PHP imports form-submitted variables into its namespace, definitions and examples of valid XML documents, one-line summaries of every PHP function, even an HTML reference. It's like going to Gallagher's Steak House and filling up on free bread. Ladies and gentlemen, may I submit the Atkins-Friendly PHP book. This is not a book about syntax or data structures. This is a book on how to use PHP in enterprise environments. During my first read, I realized around page 126 that I had already learned as much as I had expected to learn and I was just getting started!
The book is very well written, with a friendly tone that is neither pedantic nor partisan. A knowledge of PHP before version 5 is assumed, and the situations tackled are very much from the real world. The focus goes beyond getting what you want to appear in the browser, too; scaling problems of very large web sites, managing a code base with multiple developers, and building your own extensions to PHP are all discussed.
The author draws most examples from a Unix + Apache + PHP environment, and MySQL is the primary database used. The examples are all in PHP5, but many ideas can still be implemented in PHP4. In other words, you can still learn a lot even if you're committed to PHP4 for the near future.
Part I of the book is called Implementation and Development Methodologies (some of these part and chapter names could be a little less clunky, even if they are correct), and the first chapter is about coding style. After that comes a thorough discussion of the new features of PHP5. These are language aspects that are commonplace in other object-oriented languages (e.g., java and python), but which I admittedly knew little about:
- encapsulation: the ability to keep object attributes and methods private or protected;
- static attributes and methods to make class functions or singletons;
- user-definable constructor, destructor, accessor, mutator, and copier functions;
- interfaces, which are like abstract classes. A class can implement one or more of these as well as extend a concrete class;
- exceptions, which allow propagation of errors and warnings back up through the function stack.
Other PHP programming concepts are discussed in this part, such as templating, using the command-line interface, and unit testing. The chapter on Managing the Development Environment includes some CVS basics as well as how to organize and keep separate your development and production environments without breaking what works. Another topic discussed is when to use PEAR classes and when to roll your own.
Part II, Caching, is where the book gets hard-core. Once your application works, how do you optimize its performance and scale it so you can have hundreds of thousands of users?
- You can use static variables to reduce recalculations, and compile your regexps.
- You can cache data on the PHP level in flat files, DBM files, shared memory, or even in user cookies.
- There are also solutions outside of the PHP userspace. The ordinary PHP process takes the text which constitutes the programmer's code and compiles into a assembly-style intermediate code. Then the intermediate code is executed. If a script is executed several times without change, the same intermediate code is created, executed, and thrown away several times. A compiler cache saves this intermediate code and reuses it. The author has developed a free, open-source compiler cache.
- There are also code optimizers, which eliminate dead code and overly-verbose constants.
- Reverse proxies also work in web sites to reduce network latency. Latency occurs when a server is stuck waiting for a request to be completed before it can execute. A reverse proxy server only collects requests, then hands them off on a high-speed network to the actual server.
- This can be made even better with content caching. The proxy can determine if the request requires handling by the PHP webserver at all. If a stale, cached copy suffices, it is served instead.
- Content compression sends your data over the internet compressed. The client's browser is in charge of decompression.
Part III, Distributed Applications, is of big importance to the developer of medium-sized sites. The author discusses the familiar topics of database interaction (including how to troubleshoot your slow queries), authentication, and session handling. Then a chapter on clustering: how to arrange multiple, redundant servers to create a robust, fail-safe system.
The final chapter in this part covers another hot topic: Web Services. Say you want to edit your weblog entries on a real text editor rather than through a web form. If you have RPC (Remote Procedure Calls) set up on your web server, you need only write a script which manufactures a request to a web service and and ships it out. What's the sales rank on Amazon of the book you just wrote? What's the weather like in Medford, Massachusetts today? These are all jobs for web services. XML-RPC and SOAP are approaching the standards state of usage, so using one of these means you don't have to develop your own RPC client or server library. SOAP is even richer than XML-RPC: it's an all-purpose messaging protocol which is in use by many of the big players in web services (e.g., Amazon, Google).
In Part IV, Performance, the author returns to the optimization question. How can PHP scripts themselves be made to run faster? There are several techniques:
- Use the apache benchmarker or other load-generating programs to determine which requests take the most time.
- Use a PHP profiler such as the one the author has written to examine your script line-by-line and determine which function calls are most expensive.
- Use a synthetic benchmarker (such as the one included in PEAR) to analyze small bits of code and discover how efficiently they do their task. Which is faster: interpolation of variables or string concatenation (the latter, at least before PHP 4.3)? If you don't have a library compiled into PHP, can you implement all the functions in userspace efficiently (not really)?
Part V, Extensibility, is for people who want to adapt PHP on the language level for their needs. This part requires a knowledge of C and a strong grip on your hat! After a discussion of PHP and Zend Engine (the virtual machine on which compiled PHP runs) internals, the author shows how to make both simple and complex extensions. You can add new functions to PHP, add a suite of library wrappers, add and manipulate classes and objects, all using pre-defined macros. In the last chapter, you can extend Zend itself to (say) implement all errors as exceptions, create a PHP Shell, an opcode-dumper, or modify the author's compiler cache or profiler.
I very much enjoyed the book. I have chosen to take the plunge into PHP5 for a new web project, partly because this book convinced me it's worth it. I can't imagine I'm going to use everything I've learned from the book, but I'm glad to know how problems like these are solved.
There are a few typos and misspellings, but that's to be expected in such a large book with limited turnaround time. Definitely recommended.
Matthew Leingang is a Preceptor in Mathematics at Harvard University. He continues to try to integrate web development into his day job. You can purchase Advanced PHP Programming: A practical guide to developing large-scale Web sites and applications to PHP5 from bn.com. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page.
Part V, Extensibility, is for people who want to adapt PHP on the language level for their needs
This is an often-overlooked advantage in PHP: the ability to use php-embed to run embedded PHP within another application. For example, our company has created an HL7 HIPAA-accelerator in C/C++; we chose PHP as the embedded language in our product--by which users can create custom data transformations.
The reason? PHP is easy to use, loosely-typed (which is an advantage in our project), fast, and of course, free. It was a great decision.
Sigs cause cancer.
most of the books don't cover the topics of cli-based php which is unfourtunate.
Things like php-ncurses and php-gtk or even how to properly debug cli apps and it is strange saying there is a large following of PHP commandline (cli) people out there.
Anyway, always good to see more books at any rate.
anime+manga together at last.. in real time.
PHP 5? Great!
I've got a bit of a complaint about computer books, in that they frequently concentrate on the latest and greatest versions and brush aside the older versions - the versions that the majority of web hosts might be running, for instance.
I was looking for a MySQL book a while back, and there were dozens of them on the shelves in the bookshop, but all based around MySQL 4 - not the ubiquitous MySQL 3 that I was trying to learn. Looking through at all the new features can be a bit dispiriting, especially when you're stuck with the older version.
Anyone else had similar problems?
Tedious Bloggy Stuff - hooray?
Sigh, I really wish these books would get with the times and start using PostgreSQL (or even Firebird) and Apache 2.x (I assume the book uses Apache 1.x since the PHP developers seem so against 2.x).
John Kerry is a Joke!
The early versions of Apache 2 really scared a lot of people away. It scared me away. Switched to Apache 1 and things started working again. Now that doesn't excuse my poor skill in the sysadmin realm, but I would doubt I am the only one who had headaches with 2.
-Phantom
I think we can add this title to the list of contradictory terms:
that onion article titiled "Student arrested for suspected use of PHP" ...and rightly so ;)
Are you intolerant of intolerant people?
This seems to be a really common misconception among readers of slashdot. The truth is this:
- PHP developers are not opposed to Apache 2.x.
- PHP is stable on Apache 1.3 _AND_ 2.x.
- Apache 2.x has a large number of new features designed to better handle high volume sites (with or without PHP)
MySQL is still the standard web-hosting provider database backend, that is why most books cover it. mySQL is very similar to other SQL dialects. If you understand SQL, PostgreSQL is easy and you shouldn't need explanation on how to run queries from PHP. The books focus on PHP, not the SQL languages... if you want to learn about SQL, get a SQL book.
Isn't that called "Perl?"
This book seems like a friendly addition to the many 100s of php books already out there. I have bought many php books and they all seem to go over the same thing, syntax and functions. But this book from the description seems to do more than simply explain functions and syntax but also usability and practical use. I am a php programmer myself and much of the problem of coding programs is high volumes of data and usage. By using a code cache system outlined in this book it would definatly allow many good programs that are out today to be used on a larger scale. I know a bulletin board I coded a year or two back could have used this, it choked at 1000 or so users at once. PHP5 is coming and it looks to me like a force to be reckoned with. While you naysayers who code perl, c, and other languages put down PHP as a pathetic language, PHP5 should be getting on par with perl and other languages.
-Rights? What rights?
I'm thrilled to death that PHP is finally starting to catch up with the rest of the world. A solid XML interface, SOAP support, and OO like behavoir are great steps toward a modern programming language. However after my experience in with the PHP 4 I won't be upgrading anytime soon. Can't deal with the constant configuration changes, changing function behavoirs, bugs, and generally moving target of a language.
Don't get me wrong I love the current state of PHP for developing small fast websites. But if history is a good teacher then PHP 5.3 will be the release which should have been called PHP 5.0. Good luck to those adventurous souls who will be running 5.0 on production servers. I hope you can tell me the dev community has grown up and stablized their dev cycle and that I can upgrade at 5.1 instead of 5.3
-- force and mind are opposites; morality ends where a gun begins ayn rand
There are times when to use a strongly-typed, "true" OO language like Java or C++ and times to use a scripting language like PHP or Perl. Part of being a good programmer is being smart enough to use the right tool for the right job. If you want to torment yourself by over-engineering a small- or mid-sized website in EJB, go for it, but respect those who like being able to get stuff up quickly and easily, with a minimal learning curve. And YES, it is possible to build secure web apps in PHP, despite what you may have heard.
When you've only got a hammer, everything looks like a nail.
Atkins-Approved? What the crap is that?!
(I know what it means, but what is it doing here?)
The Sacred Chao says, "MU".
The issue is not weather PERL or PHP or C is better than the other.
Languages are just tools. Writing good software is a reflection of one's ability to plan, use OOP, and troubleshoot code, just to name a few.
When faced with a problem that needs solved, you examine the problem, and select the most appropriate tool(language) to get the job done, and hopefully you apply good software writing skills to the solution.
Even if you think PERL or something is so much better than PHP, but you suck at writing good software, your software is going to suck.
PHP was originally developed to make web programming easier in the same way Bash makes certain operating system tasks easier. PHP:Web::Bash:OS. ... The problem is you can't have both Bash-like scriptablity and Java-like power/maintainability. So PHP will take the road of Visual Basic -> VB.NET.
PHP5 is impressive, but it appears to be trying to change its scope and here is why. Like Bash, PHP is a big time saver for small programs, but is more difficult to write and maintain as the program gets larger and more complex. The features added to PHP5 will let it scale better, but it will lose its Bash-like advantages. It is trying to move into the arena with Java, ASP.Net(?Maybe), Python, Ruby,
After seeing MY limits with PHP I moved to Python although I still use PHP for simple web scripts. In my opinion, PHP5 is a new language in an old arena. You should choose the right tool for the job, and if you need the new features in PHP, have a look at a powerful, weathered language like Java, Python, or Ruby, or (add your language here).
You ought to be using PEAR's DB class anyway, which abstracts away most of the differences in dialect.
Tom Swiss | the infamous tms | my blog
You cannot wash away blood with blood
I'm about 3 months into a ~5-6 month project in PHP. I had never done anything nearly as complicated as I am now, but I have done a lot of PHP programming. Mainly things that took 2 weeks or less.
:)
I bought this book near the beginning of my current adventure and I learned a lot from it. It's not the typical PHP book that just mirrors the php doc web site. There's a lot of great information in there. I'm still on PHP4 but that doesnt matter, the concepts still apply.
Thumbs up!
Joseph?
I am a sysadmin by profession, working at a mid-sized ISP in Toronto. I chose to be a sysadmin because I don't really enjoy programming -- but the nature of the job dictates that I code to improve efficiency or functionality. Recently I had to work on an in-house web application, and I chose to do it in PHP, but quickly found that the relatively small webapps I've worked on in the past were not much preparation, so I bought this book..
To borrow a phrase, "in a nutshell", this book is excellent! Some of it is beyond my skills at the moment, but I appreciate every bit. The author covers OO in a way that I understood, and presented real-world solutions that helped me understand. But, IMO, the best part isn't the PHP, it's the operational theory -- the real problems that sysadmins and web programmers face with large websites, caching, load-balancing, scalability. This made the book worth the $80CND I paid for it.
I highly recommend it!
-- Steve.
I see a lot of posts making 'fun' of PHP/Apache/MySQL. Especially things like large scale applications, hard/difficult maintenance on larger projects and not good at scaling.
Well. That might be true.... For those few sites which actually DO require 'scalability', easy maintenance when the project get bigger and the target is millions of hits per hour/day for some really heavy computations and what-not.
But there are SO few of these projects around. So for all of you who thinks php stinks at least try to use the right tool for the right job. From my experience in web-application development in Norway almost every large software company will recommend some closed source, inhouse made, 'superheavy' application for whatever site you want to have. They will use every argument you post here to put their software in a better light than some 'light weight solution' like PHP/Apache/Linux/MySQL/postgresql.
Seriously, almost no web-sites in Norway targeted at norwegians will ever require 'large scale' solutions. There simply aren't enough people around. Still the companies will push forth their solution on unsuspecting customers.
I had a e-commerce site I made (using php/apache/mysql, python/perl for backend functionality running on TSLinux), reviewed by a respected IT-consultant company in Norway (Bekk - http://www.bekk.no/). Their conclusion was that it was a good solution, well written, but.... "It should have been made in a java/C# or something like that" Why? Because of scalability.
It's just absurd. They really don't take into account the target marked for the solution. And the current system setup is running just fine and dandy without any trouble. Should the number of visitors increase ten-fold (which it never will), well... Add some slave database servers and more webservers.
Suddenly you have the board of directors going: -Uhm, why didn't you write the system in Java. We hear Java is a good thing. Java is scalable. Java is more secure.
Why? Because it took me such a impossible short time to make the site with php and it's been going for 2 years now, without problems. That's why.
The solution they would have otherwise chosen would be 10-100 times more expensive, would require expensive servers and would probably take years to develop.
I ran across a used copy of this book in The Strand and have to say it has taken its place next to The Cookbook on the shelf of Truly Useful Books. All the "advanced" php books I had found before this one either had a three or four page spread on objects and classes or (in the case of one awful Wrox book) scads of code with little useful description of the considerations that went into its architecture. If you're coming to php from a non-coding background, you'll find that most books seem to stop just before the discussion gets truly interesting (and useful). No, I don't already know how to make use of inheritance, and telling me that it involves extending a class without describing why I would want to do that and how to design classes so it can be done intelligently and powerfully is pretty useless.
This book deals with those advanced topics in substantial depth. Want to know what strategies should be considered in deciding how far to abstract database classes? Want an in depth discussion of preformance caching? Care to contemplate the values of various distributed architectures? Interested in Zend engine internals? From coding style clear through application benchmarking, this book covers it, and it covers it thoroughly and engagingly.
grammar-lesson free since 1999. (rescinded - 2005)
you are a ridiculous karma-whoring troll... this is not information, this is what Rasmus has been saying for a while because not all php extensions are thread safe yet. And Rasmus isn't even opposed to apache 2, he's opposed to people encountering an error with those non-thread safe php extensions. After all, Rasmus IS a core apache http server developer as well.
What features does PHP have which make it especially suited to form and database interfaces? Many languages have easy to use CGI/FCGI/Server API's; many have HTML-embedded versions and high quality template libraries; many have database libraries which easily rival and surpass those of PHP, and many have fancy dynamic form generation and processing libraries.
;)
PHP's far from best-of-class in any of these respects in my experience; only pervasiveness is in it's favour, and running my own servers, that isn't much of a conern to me.
Give me an example of how easy it is to interface a form with a database, complete with validation and listing using PHP in ways other languages can't match. In fact, show *anything* which you can do more cleanly in PHP than any other language, and you'll be on your way to having a decent response to the grandparent poster.. and me
OK, I'll byte. (1) Database access from a website. (2) Form manipulation. Name one other language or system where it's easier to dynamically create a set of html pages with data extracted from a database. Or a language where it's easier to get and use data from a form filled by the user.
Are you kidding ?
1) Java's db api is much more cleaner and database independent, You don't have to rewrite your function calls to switch the database implementation (e.g. moving from mysql to postgres and from postgres to oracle, in java you will only have to switch the string which chooses the db driver, in php you will have to rewrite all the code implementation that has [dbname]_connect, [dbname]_query etc. calls.). the same goes for perl. and python. imho this is seriously f_cked up in php, using the word 'clean' here is absolutely n00bish. and how to you update a blob from php ? (thinking SELECT bar FROM boo FOR UPDATE) ? it's simple, you just can't.
2) every proper MVC system has an implementation on DBForms which creates default forms from database structures without needing any kind of input in the code except the table name (input fields types & values are generated/validated/handled automatically). in php i have seen such features only in frameworks alike (php doesn't have any kind of dbforms implemented by default). so php doesn't really make anything "easier" here.
the worst in php in my experience is that i have to worry about how to get & feed my dates'n'times to the database, in java it's very simple, i always have one type of timestamp, no questions asked. in php i always have to be very aware of my DB behind the datamining cause it doesn't give me the same type of variables while asking them from mysql/postgres/oracle/sybase, if i want to compare the query result from different database types, i'll have to convert the timestamps in my code to compare them. this is pretty much absurd. at least for a "high level language".
so i can't really see how php is superior in any way.
it's backward compability is mostly zero. the dudes over zend just think that hey, let's make now php5 and break the whole OOP stuff that we had until now. (we're probably going to rewrite our 'framework' over here, to make it work again.
besides until there's no threading and variable sharing possibility, it's still far behind perl & python.
for a schoolboy, php might be cool. for a developer that has been working with code since 1990, it seems like an vegetable hamburger (sure it's edible at some times, but i prefer pizza,pasta or a proper meal with some meat in it.)
I'd tell you the chances of this story being a dupe, but you wouldn't like it.
I bought this book a couple of weeks ago. It's very good. I like the way it covers the general topic of "how to write applications well" as opposed to focusing purely on writing in PHP.
My only criticisms of the book are: (1) It would be nice to see more OO patterns stuff in there (particularly database access patterns), (2) There are a couple of mistakes in the code that got me puzzled for a while. On the whole though, an excellent read.