Elegant PHP Architectures?
akweboa164 asks: "I work as a lone developer creating small to medium scale PHP/MySQL websites for different clients. I have been doing this for about two years now, and have tried different things as far as website layout/architecture goes. With sites that use the fusebox architecture, front controller (thanks J2EE), N-tier, to having a simple 'include(config.php);' line at the top of every file, I am left with the feeling that all of the sites I have created are 50% elegance, and 50% nasty kludge. I am left with a sinking feeling because I know that they could be better, but I lack to expertise and experience to make them that way. I am looking for overall architecture that is open and fits within the constraints of PHP (ie. relying little on OO) and separates logic, makes updates easy, etc. I wanted to ask Slashdot's crowd of web developers what their most elegant code layout/design web solutions were, and what advice would you dish out to new developers, as well as seasoned professionals."
(Sorry about the code formatting. Slashdot's messing with it, and dinner's on, so no time to futz with it).
I make few claims to writing elegant PHP, and I'll generally sacrifice a few extra CPU cycles if it will save programming time. I have yet to run into a situation, even on high traffic sites, where this isn't a worthwhile tradeoff, as long as you're not writing horrendously inefficient code. If there are bottlenecks, I'll look to sections of code that are getting hit a lot and optimize on that level. You might have guessed that I'll take the performance hit and use objects if I feel like it will make my job easier. There are fancy names for most of this stuff, but never mind those for now.
What I do depends largely on the scope of the project, but there is one rule that I follow without exception. Nothing goes into the page that's being displayed but control flow statements and variable output. No assignment, no (god forbid) database calls, nuthin'.
For simple, one page, this-will-be-dead-in-a-year stuff, I put this at the top of the page:
and all the work goes into index_code.php. Beyond that, for this level of work, I don't worry much about elegance beyond the usual rules of breaking discrete bits into functions rather than allowing everything to string on for screens and screens of scrolling. This is mostly for my own sanity.
if($foo) { doStuff(); } else { doSomethingElse(); }
is much easier to make sense of than if all the work is sitting in between those conditionals.
For larger applications, I use a config file that contains any configuration I might need. Again, as little logic as possible. This is likely to be shared site-wide. An initialization file, also often shared, contains any beginning work that might need to be done. Checking to see if variables should be pulled from $HTTP_POST_VARS or $_VARS, calls to authentication routines if necessary, etc.
This will be driven from one file who's job is to figure out what needs to be done, and dispatch the work accordingly. Again, depending on scale, this may also contain common footers and headers. For bigger projects, all this does is dispatch the calls, and HTML is pulled from a template file, with content being inserted into it.
The dispatcher will call the appropriate code file and a matching file that contains the HTML and any required control flow stuff (as above) for content display. The code file doesn't contain anything "deep." Anything remotely heavy is done with classes included from a lib/ directory.
This structure gives the following benefits:
One last note. I don't use a templating engine. Things like smarty are nice and all, but with a little discipline, you can achieve the same effect with no added complexity.
Seeing as the post has a zero flame content, I will add that nothing I do in PHP ever feels "elegant." For me, PHP is a pragmatic choice (widely available). The language itself (to me) has a cobbled-together feel. I'm sure that will change as it matures, but I find that things I do in PHP often have a cleaner feel in perl. I'm learning Java, and so far I'm getting the impression of language-elegance from it as well. On a purely aesthetic level, I think the language you chose has a strong impact on how elegant your solutions feel.
This is the voice of World Control. I bring you Peace.
I am looking for "best methods" for mySQL/PHP, after hacking away for a year or so now building web apps, i want to do it the right away, using OOP where appropriate, and making using of proper formatting and commenting.
Please, show me some really well done mySQL/PHP stuff, who is setting the trends?
Cloud City Digital: DVD Production at its cheapest/finest
PHP5 promises great features, but PHP4 still lacks lots of OO concepts.
You can do OO-like stuff without the points above but at the expense of no encapsulation and ugly hacks.
Some elegant constructs are hard to achieve in PHP, a statement like this (in java) would have to be dereferenced one by one by hand:Somebody who has already done some OOP would be able to find workarounds but PHP would not be a good way for a newbie to learn OOP.
Design your urls so that they're content based, and not implementation based, so where possible hide PHP from the user. Hide filename extensions from the user unless they need them. Use slashes to show content hierarchy (eg. domain.com/story/2003/6/4/ rather than domain.com/story.php?year=2003&month=6&day=4). The HTTP GET key=value pairs should be avoided where possible, unless there is no hierarchy or many items. You'll probably need url rewriting for this.
The url should pass to a script that checks the cache, and obviously request a fresh copy if it needs it.
The backend architecture depends on the app. PHP is usually for the web, and elegant architecture for HTML involves themes. Here you have three options,
Building the page as a string means that it's easier to have HTML flaws caused by one module affecting another (as PHPNuke has found). However, this is the most flexible method, if you want bizarre HTML. Dealing with strings is the older way of doing it, and I don't have much good to say about it this. In many templating engines the goal is to try and invent a simpler syntax, and then 2 years later they've implemented their own programming language. There is no such thing as simple logic when it comes to layout and HTML, and these "simple" languages often have little thought put into them, and don't allow reuse, or extensions via modules. They often end up being hacks. There are some mature examples that have solved this problem (PHP Smarty, who have simply implemented PHP in a templating language!) and these may be suitable.
Building the page using an OO means that you have a IMAGE object that has properties such as ALT text. That body object can only have certain other objects attached. You have a programatic way of dealing with a page, and you're not limited to a templating software's mini-language. However, you'll probably need to be a programmer to change the themes so you can't hand the code off to designers. It's the ASP.NET model, although there are better ways of doing it.
Building up a page in XML is elegant, in that you can refer to an XML node and attach/remove branches. You can pass nodes to PHP modules and let them attach content, knowing that all tags will be closed. You can enforce a schema/dtd on your content, and maintain a high-level language up until the moment that you publish to HTML, probably using XSL-T to theme the page.
The XML method is the best balance, IMO. XSL-T is very suited to formatting HTML, and if you want you can go to PDF via XSL-FO quite easily. I recommend building an XML file like XHTML 2.0 and then XSLTing that down to XHTML1/HTML for the cache.
As for how you handle the data, I don't really care. Personally I'm waiting for PHP5 to bother OOing my PHP.
My main gripe with PHP is that not enough is included in the default build that comes with distros and is offered for windows download. So that the generic hosts don't have the feature you need. The people who care about trim build know how to trim it more than those who don't care and end up avoiding features.
I was trying to respond earlier, but Slashdot still haven't unblocked a large...large range of IPs from posting (presumably it's not something I've done, as this account is available). Don't even bother emailing them folks, my 3 emails haven't got one answer :(
--Giving to trolls for the benefit of us all
[disclaimer: I'm a Drupal contributor] ;) cleanliness. /. home and withstands the load. I use Drupal to power different sites, from personal blogs to corporate intranets, and plan to use it as a base for other completely different projects.
Drupal is a CMS which doesn't use the OO features of PHP, but has nonetheless an OO design: for example all content is a "node", and you can "subclass" a node getting a story, an image, a forum topic etc.
It uses hooks so it can be expanded easily; it has both themes a-la *nuke and templates. Of course it has a good user management system.
The core is maintained by few people (not me) in a very strict, almost maniacal
It's fast and powers sites like Kerneltrap which sometimes is on
It also has a very active community.
Of course it has its own faults and deficiencies, but we are working to fix them.
Here is a recent review of Drupal.
Let's say you want to use only one connexion handler in your database class (so that objects inheriting from it can use shared "insert" and "update" methods).
PHP uses persistent connections for both mysql and postgresql (which i know), so I don't need to use only one connection handler, PHP will automatically use the same db connection anyway
These two examples are ugly, but only because of the language limitations.
Nope, poor design again. And I think that you are still missing the point. The language has limitations, but that doesn't mean you have to completely drop the idea of using its OO features when they are applicapable; well if you really really need OO don't use PHP, but that's a completely different issue.
--no sig here