Slashdot Mirror


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."

118 comments

  1. Relying little on OO...? by simon13 · · Score: 3, Insightful

    Quote:
    I am looking for overall architecture that is open and fits within the constraints of PHP (ie. relying little on OO)...

    Why relying little on OO? What's wrong with PHPs classes and objects?

    Simon.
    (a semi-newbie to PHP)

    1. Re:Relying little on OO...? by ptaff · · Score: 4, Interesting
      The model is still incomplete.

      PHP5 promises great features, but PHP4 still lacks lots of OO concepts.

      • No private/protected/public
      • No static class attributes
      • No abstract classes nor interfaces
      • No function overloading
      • Still experimental aggregation/composition


      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:
      object.person.bart_simpson.say("Bite Me!");
      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.
    2. Re:Relying little on OO...? by thebatlab · · Score: 2, Informative

      Actually the following:

      object.person.bart_simpson.say("Bite Me!");

      wouldn't need to be dereferenced by hand.

      However, this would:

      object->person()->bart_simpson()->say("Bi te Me!");

      Method calls that return an object can't be immediately dereferenced in the same statement. Those would have to be dereferenced one by one.

      But I know what you mean though. It sucks that you have to do that :)

    3. Re:Relying little on OO...? by rempelos · · Score: 3, Informative

      PHP5 promises great features, but PHP4 still lacks lots of OO concepts.

      • No private/protected/public
      • No static class attributes
      • No abstract classes nor interfaces
      • No function overloading
      • Still experimental aggregation/composition

      ok PHP hasn't the great OO features that other languages have (like java), but most of the PHP programs are written by one programmer and for producing HTML code which isn't the same thing as developing huge projects in an enterprise logic.

      You can do OO-like stuff without the points above but at the expense of no encapsulation and ugly hacks.

      OO is all about encapsulating and ugly hacks are made because of ugly designs. There is a tremendous advantage when using the OO features of PHP, for example you can create a class that encapsulates the database connection and all operations to it.

      A very good example that demonstrates what you can do with the OO features of PHP is PHPlib, it has everything the original poster asks except it's based on OOP.

    4. Re:Relying little on OO...? by mikehoskins · · Score: 2, Insightful

      Maybe this isn't *quite* what you want, but sounds close to your requirements. It also costs money....

      I love the product I'll mention, below. I'm not selling anything, either, but am just a "hooked" developer.... So, here goes.... (No flame wars, please.)

      I'd look at CodeCharge Studio at their http://www.codecharge.com/ web site. It generates excellent PHP, does excellent database and forms work, and lets you adapt the code it generates. It's also a full-blown IDE.

      Now, it DOES make heavy use of OO, but I think it's still based on OpenSource API's.... The source code it generates is YOURS to do what you want with it, provided you buy the product....

      At least you can have a commercial code generator for your choice of PHP, Perl, ASP, CFML, JSP (plus servlets), VB.net, and C#. It also generates Unix/Linux and Windows-compatible code that runs on a multitude of databases. It also generates CSS or non-CSS code. It gives you *huge* separation of logic and presentation and uses an application layer which is best suited for the language you want.

      It lets you customize your code and tracks your changes, provided you use their IDE. It's not 100% perfect and doesn't generate reports very well -- yet. It probably does about 80-90% of what you want, though -- with VERY little effort.... I'll admit that it has a few day learning curve, for people not familiar with Visual Studio-like IDE's. (It's not owned by Microsoft but requires Windows to generate code.)

      Heck, try it for a few weeks for free.

      Think of it this way, follow the 80/20 rule. If 80% of your code is produced by a code generator and can quickly give you a working prototype you can show your customer early in the process... The other 20% (especially if it is just a customization of what's written for you) is easy, most of the time... It gives you more time to make more money, to do bigger jobs, and to do a better job.

    5. Re:Relying little on OO...? by Anonymous Coward · · Score: 0

      PHP object access/creation/etc. is SLOOOOOOOOOOOW. Last I looked, you take a 30 to 40 percent performance hit using objects as opposed to plain old function calls and such. This sucks, since really the only benefit to PHP is speed.

    6. Re:Relying little on OO...? by Pflipp · · Score: 1

      Hmm... I find this a bad example anyway?

      From Object to Bart Simpson: that's a generalization/ specification, but the notation is more or less a class namespace thingy (either that, or an aggregation -- like System.out.println()).

      This stuff is more confusing than the average teacher's example :-)

      --
      "We can confirm that Debian does *not* ship the version with the trojan horse. Our version predates it." [CA-2002-28]
    7. Re:Relying little on OO...? by dash2 · · Score: 1
      Now, it DOES make heavy use of OO, but I think it's still based on OpenSource API's....

      WTF does this mean? How is object orientation incompatible with open APIs? Do you know what you are talking about, or are you just a marketing idiot?

    8. Re:Relying little on OO...? by Tablizer · · Score: 1

      Why relying little on OO? What's wrong with PHPs classes and objects?

      At the risk of being modded down as a troll, frankly there is no objective open evidence that OOP is superior. All the cliches about reuse and abstraction and making long-term maintenance easier just do not hold water upon closer inspection.

      Sure, OO may fit the way that *some* people think better, but every head is different.

    9. Re:Relying little on OO...? by ptaff · · Score: 1

      OO is all about encapsulating and ugly hacks are made because of ugly designs. There is a tremendous advantage when using the OO features of PHP, for example you can create a class that encapsulates the database connection and all operations to it.

      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). What you'd do in a real OO language is to use a class attribute, shared by all your class instances. Now there's no such thing as class attributes in PHP, so you have to <don't_do_this_at_home>use global variables</don't_do_this_at_home>.

      In some contexts, using a class method won't work. So instead of a clean class::method($param), you have to use:
      call_user_func(array("class", "method"), $param);

      These two examples are ugly, but only because of the language limitations.

      The fact that usually PHP is used to produce HTML is irrelevant: it's just an interface. As lots of in-house programs consist only in a front-end to a database, a web interface is often enough.
    10. Re:Relying little on OO...? by mikehoskins · · Score: 1

      That's not what I meant. I was answering two *separate* points he had in his request. He wanted little use of OO, but strong use of OpenSource API's.

      Did you read my comments in the context of his request?

      In other words, this product does not address every goal he had, but many of the things he wanted are in there.

    11. Re:Relying little on OO...? by rempelos · · Score: 2, Interesting

      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
    12. Re:Relying little on OO...? by pacman+on+prozac · · Score: 1

      in a real OO language is to use a class attribute

      kinda like a reference to your database object, or any other object inheriting from it. Then to call $this->db->query(). You could possibly even just include() the db class and db::query() from your object as php will use the same mysql connection as the poster above mentioned.

      you have to use global variables

      Not always, thats just one way. Each update to PHP brings changes such as tighter variable types and enforcing the syntax more, imo its maturing into a nice language and PHP 5 should be interesting.

      For websites that is... :)

    13. Re:Relying little on OO...? by simon13 · · Score: 1

      Yeah, you may have a point.

      As far as web backend development goes, I haven't really seen much of an advantage using OO as opposed to just batches of functions. As you said, it can depend on how your mind works. It does keep things a little neater, but is it worth it at the cost of performance?

      Can anyone offer a particular technique they've used in PHP which could not have been done without OO?

      Simon.

  2. Java View/Model/Controller by Ann+Coulter · · Score: 0, Offtopic

    I have always favored Java's architecture. It is a very organized and powerful solution. By combining Java with MySQL, one can implement the View/Model/Controller design pattern in a web site. The Java applet and web documents will function as the View whereas MySQL implements the Model and the Controller will be the interface code for MySQL. Using Java in this way will lead to solid code akin to Apple.

    1. Re:Java View/Model/Controller by amorico · · Score: 4, Informative

      This makes so little sense that I can only assume that Ms. Coulter is laughing her butt off at the moderators.

      There is no Java MVC for the web. You either roll your own or use Struts or Webwork or Maverick et al. MVC is a design pattern, which was correctly stated.

      That, however, was the extent of any correctness. The Model is the data, which in her case would be the MySQL held data. The view would be a generated html page, JSP, Velocity Template, XML/XSLT pipeline, or whatever display technology you would use. The controller would be something that receives requests from a web browser and then decides what action to take (pull data from a database, massage it, return it, and show a results page). Accessing the data is handled by Data access objects or delegates.

      If you don't know what in tarnation someone is talking about, don't moderate it down or up, just leave it.

      I am going to start using that line at work though. "If we use java this way we will be akin to apple!"

      --
      "The plural of anecdote is not data." -- Roger Brinner
    2. Re:Java View/Model/Controller by Kytakh · · Score: 1

      I agree with you that the apple comment was slightly askew, but what about using servlets as the controller? Then there are any number of different views (ie jsp) and data models you can also use within this MVC approach. This is pretty basic stuff but has been around for years. It has little to do with your point about the moderation tho...

    3. Re:Java View/Model/Controller by amorico · · Score: 1

      My point was that a very misleading comment had been modded up. THat would be unhelpful to someone who knew nothing about MVC. I understand someone making a mistake and posting it, but not modding the mistake up so that others think it is somehow valuable information. Anyone who knew what the post was trying to express (or mislead others about) woudl not have modded it up.

      --
      "The plural of anecdote is not data." -- Roger Brinner
  3. Dude, don't worry about it. by Anonymous Coward · · Score: 3, Funny

    95% of all Internet endeavors go bust within the first 2 years, chances are, you won't have to touch the code again. The other 5% are all porn sites, in which case, you don't want to touch the code to begin with or maybe you do... Well dude, use a front controller like Jakarta Struts.

  4. Bite the bullet... by Anonymous Coward · · Score: 0, Insightful

    ...move to Common LISP. Paul Graham says that the problems you're having are because of the lack of expressiveness of your language. People don't write software; they write domain languages, dude!

    1. Re:Bite the bullet... by tweggen · · Score: 1

      I don't think this is -1 troll but a very important thruth.

    2. Re:Bite the bullet... by mrami · · Score: 2, Informative
      The common lisp part is probably a bit trollish, yes :) but the truth is there. Architectures like J2EE and PHP are very concerned about the mechanics of building the page (very important), but I don't see much structure regarding encapsulating user flow (also very important). True, there are wonderful things such as Struts that move far closer to that goal, but even so you end up managing multiple views, and maybe multiple controllers, when all you really want to say is something like
      user =
      readPersistent(User.newForm(username, password; username == $.username && password == $.password),
      "Please enter your username and password");
      doStuff(user);
      ...
      Ah, well...

      As for PHP, I use:

      • every file includes a common.php that defines your common functions, including one that generates a templated page.
      • use front controller when I can
      • data access objects and transfer objects (form and persist), with a nice generic renderer functor s to HTMLize your transfer objects.
      • data-intensive classes (like transfer objects) usually end up being arrays with type signatures as opposed to actual classes. If you're using your nice generic renderers, adding a column to a result set can boil down to a change in one place. I still call the classes, though, because to me they still are (I do dispatch based on their "type").
      I usually use this architecture. DB side: I have a DAO for each table used in a single-table query, along with a specialized DAO for each distinct join situation. These usually pass back a class that knows 1) the data and 2) whether it's a singular or tabular result (whether it was intended to ever bring back multiple rows). I then have a generic result renderer that will render anything, plus any specialized renderers. UI side: I have a generic form class that has a list of labels and references to the fields in the model they represent (or temp field definitions if the fields are not persistent). Then, of course, a generic form renderer + specialized. The rest is usually cookie-cutter.

      The caveat here, of course, is that I write mainly business apps, so consistency is the key. The genericity you find all over the place is a win for my kind of app.

  5. web apps just aren't there yet by MikeRepass · · Score: 5, Informative

    I feel ya.

    Personally, I deal with different technologies, using ASP.NET (the horror!) to craft a rather random assortment of inhouse management tools for an IT organization, but many of the issues we face are the same. From ye olde days of ASP 3.0 with the ugliness of "includes" to a modular, n-tier approach, I'm always left with an unshakeable feeling that things could have been done better. The kludge that is modern web application interface (that is to say, HTML, J(ava)Script, etc) are too scattered and poorly supported to make anything approaching an "elegant" web application. (Btw, I'd love to be proved wrong here ...).

    Here are the few suggestions I have which I can confidently say have improved my productivity. There probably the same things that everyone has come across, but maybe if I throw them out here I can invite some discussion.

    Separate the task-at-hand and its implementation logic from the presentation layer. For instance, I normally write all of my business logic and database code as if it were just going to be an entirely separate library, and not particularly targetted towards web dev. This not only enforces solid library design principles, but allows me to debug and test using simple command line interfaces to the library. Approaching your code from a new direction (in this case simple user apps) frequently opens up entirely new ideas and perspectives. Once you've done this, the majority of your "behind-the-scenes" web code can just be a wrapper for this library, and then all you have left is the presentation logic. This has helped me immensely in the areas of scalability/integration and portability.

    Second, never ever do any cosmetic presentation work until you're absolutely sure you have a beta (or better) quality base of business logic you're prepared to stand by. Adding the presentation logic to a web app too early is sort of like munging in command line options to a good ole console app: if done improperly, things quickly get out of hand and you have to code in more global scope hacks than you'd like to admit. Personally, after many bad experiences with this problem, I do *all* my testing on blatantly ugly hand-crafted html pages until I'm sure I've got things right.

    Third, don't focus on a "page" as a discrete, targeted development object. Rather, the actual pages should be afterthoughts. Try to engineer solid "user-interface" components, and then plan on the final web pages as simple composites of these components. I estimate that, when I sketch out my initial concept of the pages and interface layer of a web app, more than 50% of the various tasks presented to the user will change drastically in scope before I'm even done developing. You realize that certain tasks just aren't needed, certain things are inconvenient, etc and using a component model to the presentation layer helps reconfiguring immensely. One of the biggest frustrations with web application is that, when different ideas are flying through your mind, its difficult to figure out all that must be coded in order to test them out. You think, "hmm this might work!" and find yourself having to chase down random bugs and make changes in five different files just to get a prototype working. Using a component model helps quite a bit in this department.

    In terms of architecture, the only vaguely successful model I've come across is (once you've got a solid library backing you up...) model your application as a set of distinct user tasks. Allow each task to develop independently, and the step back and look at where the overlap is and what components are a good candidate for integration. Taking things on a task-by-task basis at the beginning helps immensely in bug detection also, because you're only focusing on one coherent progression of logic at a time.

    I realize that most of this is probably old news to any qualified web dev, but this is the stuff I have to continually force myself to do after two years in the biz, so perhaps it is of some use. Any comments, suggestions, rebuttals, etc I'd be glad to hear.

    Mike

    1. Re:web apps just aren't there yet by Anonymous Coward · · Score: 0

      > Personally, I deal with different technologies, using ASP.NET (the horror!)

      I know Java/Struts and think about using ASP.NET too.

      What is so "horror" about ASP.NET? That all the code is scattered? The missing/bad MVC concept?

    2. Re:web apps just aren't there yet by Anonymous Coward · · Score: 0

      Eh?

    3. Re:web apps just aren't there yet by rfsayre · · Score: 1

      Control Flow in Apache Cocoon is one approach can really speed up development and reduce boilerplate code.

    4. Re:web apps just aren't there yet by Tablizer · · Score: 3, Insightful

      The kludge that is modern web application interface (that is to say, HTML, J(ava)Script, etc) are too scattered and poorly supported to make anything approaching an "elegant" web application.

      Agreed. HTML+DOM+JavaScript is optimized for e-brochures, and not business forms. Web stuff gets tricky when one tries to make HTML forms behave like real GUI's.

      What we need *is* real GUI's over HTTP. Candidates include XWT, XUL, and SCGUI (my pet fav).

      However, if we must live with HTML+DOM+JS for now, then my advice is to try to emulate GUI's using a persistent server-side copy ("view") of a web form. Echo this back to the client after updating it. Whether this "view" is stored in RDBMS or objects is a personal preference that I won't go into here.

      For more on my opinions on this, see:

      http://geocities.com/tablizer/webstif.htm

    5. Re:web apps just aren't there yet by Anonymous Coward · · Score: 0

      Yeah -- that's exactly right. Creating a "meta-html" was somewhat of a good idea, because (in theory) you can turn web-development into a Visual Basic-like declarative system.

      However in practice, the metalanguage doesn't map cleanly onto cross-browser HTML, nor does it provide all of the features possible from hand-coded pages. The solution is "custom controls", but in practice those are probably no better than spaghetti pages full of interface logic. (Of course, VB has the same problems which is why you see those VB "experts" mastering a 3rd party grid control or abusing Win32.)

      I guess I agree with the parent post -- nothing I've used really seems like it's "there" yet.

    6. Re:web apps just aren't there yet by King+of+the+World · · Score: 2, Insightful

      Thanks, reading now...

      Don't forget the CSS. By using overflow:auto on a fixed box you can make scrollbars, and emulate many types of layouts previously impossible without crummy old frames.

    7. Re:web apps just aren't there yet by code+shady · · Score: 1

      What we need *is* real GUI's over HTTP. Candidates include XWT, XUL, and SCGUI (my pet fav).

      What about converting "web apps" to web services? seems like this would solve the problem rather nicely, at least foo certain types of applications. You can write the back-end in whatever you want, using standard web languages, but instead of an http front end, you just write up a client, which would be relativley easy, as all it does is gather the info and send it out over http (or SOAP). Since the fornt end form is done nativley anyway, it can behave exaclty how you want.

      --
      Look out honey cause I'm usin' technology
      Ain't got time to make no apologies
    8. Re:web apps just aren't there yet by Anonymous Coward · · Score: 0
      The solution is to get back to the good old days of client-server. Write all your bussiness logic without any presentation bits (as per your suggestion), disclose them using XML-RPC or SOAP, and build a front-end using a proper rich web client platform such as XWT, Thinlet or even Flash MX, which speacks SOAP using the connector add-on.

      DHTML sucks to do stable and responsive UIs in. And even if you manage stable and responsive, you'll still end up with code like
      if (netscape4) { ... }
      all over the place.

  6. Some suggestions by Alpha27 · · Score: 5, Informative

    I like PHP alot for web development. I found it easier and less to code when compared to perl (I've done both for 3 years each). You've made a good choice with it. I haven't tried python, but i do hear good things about it.

    One important advice I would give is.... learn from your repetition. Meaning.. if you see that you code very similar functions or code segments that very ever so slightly, maybe there's a new function in there, that could emcompass them all.

    For example:

    • writing tables: I wrote a class to take an array of array, and spit out a table structure. Beats having to write echo statements with td tags, mixed with variables.
    • simple dababase functions: I've knocked out a number of lines using simple code that does the same 3 steps into one function.
    • object oriented code: definitely helps out.
    • apply theory/concepts to work: I've seen the Model/view/controller example applied to non java languages. As well you can use cool things like XML/XSLT to handle data/presentation, there by allowing for multiple display formats.

    some times the elegance is in the hack. I rewrote an art project at the company I work for, using our product for the front end, and php for the backend within 6 hours. He originally wrote his from concept to product in a year. Not bragging, just saying. =)

    Look into some of the templating engines, like smarty.php.net, it's srecommended at a number of sites (I haven't used it yet), but it will allow for cleaner code, and that's what is important. Accessing code you can easily fix, and change the presentation when needed.

    1. Re:Some suggestions by Anonymous Coward · · Score: 0

      I rewrote an art project at the company I work for, using our product for the front end, and php for the backend within 6 hours. He originally wrote his from concept to product in a year.

      Look like the guy did a very good job, he came up with a design that was so good it could be reimplementeted in 6 hours...

    2. Re:Some suggestions by Phouk · · Score: 0, Troll

      I like PHP alot for web development. I found it easier and less to code when compared to perl (I've done both for 3 years each). You've made a good choice with it. I haven't tried python, but i do hear good things about it. You've made a good choice with it.

      So you know two languages for web development, and have "heard about" a third, and feel knowledgeable enough to put out a general recommendation?

      Man, that is +1 funny!

      --
      Stupidity is mis-underestimated.
    3. Re:Some suggestions by Alpha27 · · Score: 1

      wow didn't know my resume was on the line here.

      the poster asked about php for web development and I respond in terms of his request. I've done enough web development over the past 6+ years, with open source software specifically, to respond.

    4. Re:Some suggestions by Tablizer · · Score: 1

      object oriented code: definitely helps out.

      I am skeptical of that. Do you have a specific code example? Many things that are put into "objects" could have been put into dictinary arrays instead, for example.

    5. Re:Some suggestions by vampiretap · · Score: 1

      How many languages does one need to know? 2 isn't bad! Sure beats none. You don't have to know twelve languages to write web apps. Get off your high horse...

      --
      GodBrain http://www.godbrain.net http://www.alienfaktor.com http://www.tril0byte.com
  7. PHP handles OOP by limekiller4 · · Score: 1

    Why avoid OOP? PHP supports classes.

    Granted, it isn't Java, but that isn't any reason to avoid them altogether or to avoid the tremendous amount of benefit that can be obtained from one.

    jason@php.us

    --
    My .02,
    Limekiller
    1. Re:PHP handles OOP by Anonymous Coward · · Score: 0

      I think the point is to not RELY on OOP features.

      Support for objects (and classes) in PHP4 is a nice convenience but it is not suitable for sophisticated object/class designs on at least two fronts: 1) speed, 2) features. AFAIK, PHP5 will have much more to offer OOP programmers/designers, but for now, it is rational to look for designs that can be implemented without significant OOP features.

      IIRC the maintainers themselves called object support in PHP4 a kludge (synatatic sugar) with the initial support added to the language "in a weekend".

  8. My PHP tips by Imperator · · Score: 4, Informative

    I don't claim to be an expert PHP developer, but I have spent a fair amount of time with it. Here's what I've found works:

    • Every file includes base.inc.
    • base.inc includes a config file based on the hostname and port--this is to allow you to use the same code to run both testing and production servers. These config files are where you keep stuff like the directories in which to store files, the database config, and so on.
    • Use PEAR as much as you can. In particular, use PEAR::DB. Since you probably use the DB in every request, open it up in base.inc and store it in a global. Also, you never know when you'll switch to a different RDBMS, and if you have to modify every single call...
    • On that note, use PHP OO to abstract away the DB. Do it logically, not "one class per table". This way, when you change the database or even just the schema, only the library files need to change. If it's a big multi-user project, write regression tests.
    • If you're using the Zend Optimizer or a similar bytecode cache, go ahead and include all the library files from base.inc so you never have to worry about doing that.
    • Use CVS. Even if it's just you.
    • Use a good template system like Smarty. Just because PHP lets you mix code with HTML doesn't mean it's a good idea.
    • Write your own classes to handle any common task, even for something as simple as getCgiVar().
    • Keep the DB schema in one file so it's easy to read and modify.
    --

    Gates' Law: Every 18 months, the speed of software halves.
    1. Re:My PHP tips by Blaze74 · · Score: 3, Informative

      Take what the above poster said, but use base.php instead of base.inc. Using .inc files is asking for trouble when you deploy it on a server that does not restrict access to files with a .inc extension and someone decides to look at database_passwords.inc

    2. Re:My PHP tips by brianlmoon · · Score: 1

      I agree. We ran into that with Phorum. Caused us some bad press where files divulged info we did not want divulged.

    3. Re:My PHP tips by damien_kane · · Score: 2, Informative

      use base.php instead of base.inc

      Not only that, but in case you have some code in base.php that is not called as a function (for example your DB link), put something like this at the top of base.php:

      if (!isset($somekeyvar)) die();

      Then make sure you set $somekeyvar in everypage. This will make sure that code isn't accidentally run when some (non-)malicious user goes looking around.
      Alternatively, include base.php from a path which the webserver does not serve, but still has access to. For example, create a path /htdoc-includes, give the $webserver read access to the files inside it, and put base.php in there.In this way there is no whay that a user could call it from a browser independant of your main page(s).

    4. Re:My PHP tips by FryGuy1013 · · Score: 3, Funny

      unless you have register_globals turned on..

      if (!isdefined("real")) die("hacker");

      and

      define("real", 42);

      would be better.

      --
      bananas like monkeys.
    5. Re:My PHP tips by pompousjerk · · Score: 1

      I'm not entirely sure (neewwwwbie) but couldn't you just use PHP's header function to create a fake 404?

    6. Re:My PHP tips by Imperator · · Score: 0

      Sure, or you could just redirect to a real 404. :)

      --

      Gates' Law: Every 18 months, the speed of software halves.
    7. Re:My PHP tips by Captain+Large+Face · · Score: 1
      Every file includes base.inc.
      If you're going to do that, why not automatically prepend the config file using the "auto_prepend_file" setting in php.ini?
    8. Re:My PHP tips by agnosonga · · Score: 1

      I use base.inc.php
      that way the code is run by default (not displayed) but you can also tell apache to handle .inc.php in a different way
      its also just a good way to tell the difference (like using .html and .htmlf)

    9. Re:My PHP tips by Tablizer · · Score: 1

      On that note, use PHP OO to abstract away the DB.

      That is very difficult unless you stick with a wimply SUBSET of both OO and relational, getting the worse of both worlds. OO and relational are two very different things that don't match up one-to-one for the most part. Further, relational can be a high-level tool if you know how to use it, not a low-level service to just be wrapped over with flat API's.

      If you mean putting wrappers around raw SQL calls, then I fully agree. But, you don't need OOP for that. One is generally not going to use enough different RDBMS within the same application to justify the syntax overhead of polymorphism. Most use just one.

    10. Re:My PHP tips by ProfKyne · · Score: 1

      Take what the above poster said, but use base.php instead of base.inc.

      No, use inc and use an .htaccess file to block all requests for files with extension ".inc". You don't want these include files to ever be executed unless it is from inside of a PHP script. As Rasmus Lerdorf calls it, "executing code outside of its context".

      --
      "First you gotta do the truffle shuffle."
    11. Re:My PHP tips by pacman+on+prozac · · Score: 1

      is there any point?

      If your include files are just classes or functions, then the user will just get a blank page. No output will be shown because no functions are called.

      If they're not just classes or functions then...er...they're wepages and you want them to render :)

    12. Re:My PHP tips by Old+Wolf · · Score: 1

      You might be able to answer something for me. I've shied away from having a "base.inc" or similar other global include file. Doing so might involve having thousands of lines code for each page load. This must take a lot of time for the server to parse, so it would greatly reduce the load capacity of the server. Is this thinking correct or is there something else going on?

    13. Re:My PHP tips by Imperator · · Score: 1

      You're very right that doing this naively will result in just what you describe. PHP will parse all those files to an internal opcode format, then execute that. What you want is for it to cache the opcode so it doesn't have to re-read/parse/compile the .php files until they change on disk. The best way to do this is with the Zend Optimizer, which is written by the same people who write the PHP engine. It's free as in beer and comes only as a binary. If you want free as in speech as well, search for "php accelerator", "phpa", "mmcache", and I'm sure there are more. (I will warn you that I've had a bad experience with one of the non-Zend caches where it failed unpredictably when the server handled multiple requests simultaneously. Because that almost never happened on our testing server, we didn't notice until it was on the production server and causing havoc. Test thoroughly. :)) All of these caches require minimal setup (though you will need root) and work automagically. With a functioning cache, most requests will actually be much faster if you include all your libraries from base.inc or whatnot, since all the opcodes were cached after the first request. HTH

      --

      Gates' Law: Every 18 months, the speed of software halves.
    14. Re:My PHP tips by Old+Wolf · · Score: 1

      Thanks, will get onto it :) I had heard from somewhere that you had to pay for the 'good version' of Zend, but perhaps it was confusion that begain with merely 'non-GPL'

  9. PHP OOP by Anonymous Coward · · Score: 0

    OOP support in PHP is currently very low. Performences are horrible but I use it anyway. Most of the time, performences are not a must so go for clean code. PHP5 will be great thought.

    I usually design an object layer under the website to access the data (read/write). All validations are done there. All that is left afterwards is to plu a user interface on top.

  10. Just Another Hacker's Advice by eddy+the+lip · · Score: 3, Interesting

    (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:

    // index.php
    <?php
    preg_match('/\/([^\/]*)\.php/ ', $PHP_SELF, $matches);
    $code_file = $matches[1] . '_code.php';
    require($code_file);
    ?>

    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 place for site (or project) wide look and feel changes
    • easily findable files for the designers to mess with. Ours are more than capable of dealing with the occasion if or foreach
    • heavy code in reusable classes, centrally located. One stop bug fixing.

    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.

  11. Please list URLS people!!!!! by heldlikesound · · Score: 1, Interesting

    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
    1. Re:Please list URLS people!!!!! by brianlmoon · · Score: 1

      Trends? Hmmmm. That is tough to say. Everyone has their own way of doing things. It is quite common amongst the available PHP applications out there (Phorum, phpBB, PHPNuke, etc.) to have a common.php type of file and/or a config.php file.

      I can't really point you to any URLs as I don't really know any. I can tell you what we do at dealnews.com. That may not be what you want, but it is all I have to offer.

      We have a library or as we call it codelib of about 300 different files. Some are classes, some are function based. When we create a new site, we create functions to access the data layer for that sites data. Then, when designing the GUI, we can simply call those functions which return us arrays. This makes working with the data easier as you don't have to worry each time what query to use and such.

      You can take this a step farther as we have done with Phorum (and others, see Smarty) and separate the output layer as well. Phorum uses a 3 layer design. The database interaction is contained in one file (big file). All connections and things that need knowledge about data access are in that file. the functions in that file return arrays where data needs to be returned. The core, as we call it, calls those functions to get the data. It then does whatever it needs to them (formatting of text, URL creation of links, etc) and creates another array for the last layer to use. The output or template layer then uses the arrays to generate an HTML page. You would probably want to just use Smarty for this. It is powerful and generic. We wrote our own as Smarty was just starting when we started Phorum 5 and we need some stuff just for us.

      If you want examples, you can check out the Phorum 5 code at http://phorum.org/. I really tend to develop most of my own stuff so I don't look at other's code much, sorry.

    2. Re:Please list URLS people!!!!! by Demerol · · Score: 1

      I'd recommend looking at the PEAR Coding Standards. I find that most of the styles of coding that I developed on my own are similar. I changed a few of my habits to conform with PEAR's standard. I don't necessarily ever plan on submitting code to the project, but I like to have a written rule and it's a decent rule, fwiw. Personally, I would like to see these guidelines adopted as industry-standard php coding style, but whatever.

      So, yeah, check that out.

  12. Page based doesn't scale by Hard_Code · · Score: 1, Insightful

    Page-based approaches (PHP, JSP, etc.) don't really scale well. They are fine for a project consisting of a handful of "pages" but once you start dealing with 10, 20, 30 pages, the metaphor just crumbles and you need to start with a new type of design, like MVC. Unfortunately, I'm sort of cynical about the prospects of modeling interactive applications (face it, a lot of these web "sites" are really "applications") on a low level REST/HTTP protocol and think something new is needed like cURL. But in the real world, if you can refactor your application into MVC and use a page-based scripting (or templates ala Velocity, FreeMarker) for presentation only, that should scale better than pages. (i'm talking scaling in complexity, not load)

    --

    It's 10 PM. Do you know if you're un-American?
    1. Re:Page based doesn't scale by self+assembled+struc · · Score: 1

      the real trick is not to use PHP on a per page basis, but as a program.

      I think of my web-apps as applications, not websites, where the browser is the display component. I write one index.php that has a "command line" (an HTTP GET) variable that defines what the "action" is (and any number of other variables necessary)

      the action defines what "page" you're looking at, and then I use a templating language (acutally, I hacked together a very ugly perl html::template port so i can use html::template syntax which i'm familar with) to acutally make the pages.

      each action is a function, so it makes for very clean code.

      and OOP is your friend.

    2. Re:Page based doesn't scale by eddy+the+lip · · Score: 1

      I definitely agree about page-based thinking not scaling. We've got an in-house CMS that has a page based admin feature that started to bother me about half way through development. It includes modules for more complex functionality that you add to each page. I would have tossed it for another metaphor, but quickly realized there was no way we'd be able to get client's heads around something without folders and pages. So I hid as much of what's actually going on as I could behind page metaphors.

      Dying for the resources for a redesign...;)

      (By the way, my perl-based development has relied a lot on HTML::Template. Very nice, lightweight solution).

      --

      This is the voice of World Control. I bring you Peace.

    3. Re:Page based doesn't scale by Anonymous Coward · · Score: 0

      OpenBSD manages with just html, and they got some quite nice pages with real nice _content_.

      http://www.openbsd.org

  13. what I do... by Anonymous Coward · · Score: 1, Informative

    I use classes extensively in PHP, as well as PEAR whenever possible. It's slow sometimes and doesn't feel as elegant as Perl's add-on modules (yes I just used "elegant" and "Perl" in a sentence, I've done some nice stuff with mod_perl and XML) but it makes your code a lot cleaner.

    Separating code and presentation: well we all should realize 100% separation is impossible, but you should try as much as possible. I've been having good luck with Smarty. Basically you write a bunch of PHP code that computes all the parts of your page, then you send all that off to template code that generates your final page. This is a good system, even if you don't use Smarty (it could just be two different PHP scripts, one is a model, the other a view/controller).

    Basically you write your code, then you do the presentation, then you go back and adjust the code, then you adjust the presentation, after a few iterations it stabilizes nicely.

    Another interesting thing about Smarty: the author(s) of Smarty inadvertantly created a new programming language inside Smarty using Smarty tags, which isn't PHP, so you have this weird feeling of programming in two different languages... and it turns out to be a great way to keep the two realms separate (at least for me).

    I would recommend trying this approach, if you don't use Smarty, you could use PHP and XSLT: PHP code that generates very basic XML containing the data you want to display, and then a Perl or PHP or whatever script that just applies XSLT and then sends the HTML to the browser.

    I think this "two-stage, two-languages" approach has helped me keep everything separate in my mind, give it a go.

    And PLEASE, use PHP objects. Someday PHP will be a "good" programming language with good OO features, get used to what it has now.

    1. Re:what I do... by brianlmoon · · Score: 4, Insightful

      And PLEASE, use PHP objects. Someday PHP will be a "good" programming language with good OO features, get used to what it has now.

      I hope you are not implying to use objects for the sake of using objects. I use objects where they are needed. But in a language that is not bound to them, they are not needed all the time. I remember someone wanted to have a String class be part of PEAR. Why on earth do you need a string class in a language with such great string functions? I have seen object overkill and it is not a pretty thing.

      Where do I use them? When I need to keep stuff "behind the curtain". We have a class to display large tabular data that we use. It is the right choice as we just call $report->addrow("data", "data"...); and the class keeps up with it all in vars for us and there is no mess.

      So, use them where they are appropriate, is my advice.

      Brian.
      Phorum.org

  14. ez systems by vudmaska · · Score: 1

    I've been checking out ez systems. http://www.ez.no/

    It's a cms system, written in object oriented php, and seems pretty comprehensive.

    I'm holding out for a good server-side open source ecmascript interpreter(maybe mono?) with built in support for xml(e4x).

    Good luck!

    --

    my other sig sucks less

  15. Re:The only elegant PHP layout... by tha_mink · · Score: 1

    The only elegant PHP layout...Is when it is rewritten in Perl

    Cue stock footage of explosion at the punctuation factory...fade to black...

    --
    You'll have that sometimes...
  16. Here's an elegant way out... Drop PHP by Randolpho · · Score: 3, Insightful

    I have a wild suggestion. If you want elegant, kludge-free web applications, drop PHP. The very nature of server-page based programming (PHP, ASP, JSP, etc.), the very act of mingling your code with your markup is non-elegant. Unfortunately, there really isn't any way of separating the two in an elegant fashion, so you're sorta destined for a kludge somewhere, but there are better ways.

    One kludge I rather dislike about nearly all server-side programming is the necessity of a connection to a relational database. Invariably, you must get into a lower level to get your data; often you are forced to write SQL for your data, and if your database is complex your queries can get pretty convoluted. There are tools to try to make that transparent, but the cure is often just as bad as the disease.

    There are better ways, however. Zope, a web application platform based on the Python programming language, is my current favorite. The big feature that I like best about Zope, aside from the excellent builtin security framework (which is head and sholders above PHP, BTW), is the persistent object database -- with it, Zope can entirely eliminate the necessity of an external database. Not that you can't connect to an external database if you really feel like it; Zope has a built in connectivity API, and there are plugins for all your favorite relational databases.

    Zope has many elegant means of managing your content, from your standard header-footer includes to context-based acquisition, to the many content management frameworks already built for you on top of Zope like Plone. Zope comes with two powerful templating languages if you don't like straight Python: DTML and Page Templates.

    That said, there are drawbacks: Zope is its own server, so you have to find a hosting company that offers Zope if you don't maintain your own servers. Zope.org lists a few free hosts on the main page. Using the object database is great, but because it's transactional your disk space can quickly bloat if you running a website whose data changes frequently, like, say, a popular forum or blog.

    As for the language changes... if you left perl for php because perl was ugly (and believe me, I agree), then you should try python. The language is elegance personified. It's a scripting language, so it lacks the performance of Java or C++ for computation-oriented stuff, but the stuff it does, and the simplicity! Often I've seen three short lines of Python code take tens of lines of Java code to accomplish the same task. Python is so readable you rarely need to comment your code if your variable names are well named. It's also fully object oriented, but if you don't like OO for some odd reason, you can do your stuff with just functions.

    Wow... what started off as just a few lines turned into a novel. Now I'm all tired and stuff. Can you tell I really like Zope and Python? :)

    --
    "Times have not become more violent. They have just become more televised."
    -Marilyn Manson
    1. Re:Here's an elegant way out... Drop PHP by CWCarlson · · Score: 1

      I wholeheartedly recommend Hurrah for Zope-friendly web hosting. The pricing isn't bad, service is great, and their servers seem to be pretty snappy.

    2. Re:Here's an elegant way out... Drop PHP by platypus · · Score: 1

      I'm too late, so someone beat me in zope worshipping ;).

      I should say that I was _never_ in the 10 years I program know for preaching my language/plattform of choice, but if you have gone to zope you'll love it and will never look back (at least surely not if you came from php/perl, and I did them both).

      Just to add two things which I think randolpho above didn't mention (just skimmed the text), these are transaction safeness (never ever write db->commit() ) and it very friendly community.

    3. Re:Here's an elegant way out... Drop PHP by Tablizer · · Score: 1

      Zope seems like one of those love-or-hate technologies, kind of like Perl. It either rubs you the right way, or the wrong way, with little in between. Some have described it as web development nervana, others describe it as "OO theorists getting carried away with kludgey concepts".

    4. Re:Here's an elegant way out... Drop PHP by Anonymous Coward · · Score: 1

      I've tried it for fun on my OpenBSD box, and it worked pretty nice. Zope was only allowed locally for testing, though.

      For my own part, I just want to put up some pages (at home) without getting hacked during the next 14.13 seconds of running it. I don't know if that applies to Zope, but Zope _do_ use WebDAV, that on MS platform at least, has had some problems...

    5. Re:Here's an elegant way out... Drop PHP by Randolpho · · Score: 1

      I'll grant you that. I love the concepts of Zope, but some of the implementations leave a little to be desired. I suppose I could roll my own if I had 3 years of free coding time. ;)

      --
      "Times have not become more violent. They have just become more televised."
      -Marilyn Manson
    6. Re:Here's an elegant way out... Drop PHP by John+Q.+Public · · Score: 1

      I've run into some serious challenges starting to use Zope... the documentation is kind of brutal and out of date, with few coherent examples of page templates or external classes. Do you (or anyone else) have non-obvious leads on how to get started building Zope Products or ZClasses beyond the docs on zope.org? Or suggestions offline: zopehelpfromslashdot at remove.this webplumbers.com

      Thanks... I'm really hot to start building stuff but not sure where to start...
      ---

    7. Re:Here's an elegant way out... Drop PHP by afroborg · · Score: 1

      Or you could use apache with mod_python - I have never used Zope but i know the python (and mod_python) docs are pretty good... //Adam

      --
      my sig could kick your sig's arse...
    8. Re:Here's an elegant way out... Drop PHP by Anonymous Coward · · Score: 0

      DTML is broken ('-' characters in variable names)

      Zope's object model is broken (reverse the stack? WTF?)

      Because the whole thing's written in Python, it's almost impossible to tell where your web server ends and your components begin. This makes the sysadmin's task a nightmare.

      Python alone, however, is an awesome langauge.

      This is not to defend PHP, which has some ridiculous mis-features:

      $string = "12345"
      foreach ($string as $char) {
      echo $char;
      }

      but Zope is not the answer. Personally, I'd suggest ASP.NET - which hauls us up away from the request/response model of HTTP, and closer to an event-driven model like normal programming.

  17. Re:The only elegant PHP layout... by JM+Apocalypse · · Score: 1

    How on earth is Perl elegant?

    I think you misunderstood elegant for unreasonably complicated and illogical.

    And what is it with elsif? If you have a grudge against the e, trying to take it out of every situation possible, can you please keep this issue locked up inside?

    PHP is just a better language in many ways. The only downfall of that is that bad programmers realize that, and learn to write programs before they learn to write good programs.

    --

    - - - - - - -
    Orppf urp mf y.ppcxn. yflcbi otcnnov C am yflcbi yr n.apb Ekrpatv (Dvorak -> Qwerty)
  18. I have been doing some interesting work... by immanis · · Score: 2

    Using PHP objects and the State Machine concept, I have been doing some things I think are unique, or at the very least interesting.

    I am unable to send you to a specific site, since the bulk of my development has been for internal sites, developer/qa tools and so on. I can however say that taking this approach has made modifying my applications significantly easier.

    I would be happy to talk further with this in email. I can be reached at the email address listed in my profile if anyone wants examples.

  19. phplib by Anonymous Coward · · Score: 0

    Check out phplib. I used it a lot back in the days when I was a php monkey :) Really loved it. I fumbled a lot with the templates implementation, which I didn't really like, anyway, any sane person would use php's xslt functions for that now.

  20. Designed urls, a cache, templating... by King+of+the+World · · Score: 3, Interesting

    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,

    1. build the page up as a string,
    2. build it up using a templating language's OO where you have table objects, and you attach row objects, which contain cell objects (similar to ASP.NET)
    3. build it up using XML (my favourite)


    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 :(

  21. Can this be done?? by metalmaniac1759 · · Score: 1

    Whenever a new user connects:

    make_secure_connection();
    do_login();
    get_user _profile();
    do
    {
    display_menu();
    }
    while(do_stuff(get_choice()));
    do_logout();
    break_connection();

    I just wish - things could be done so easily on the web. Most of the web sites that I'm developing could very easily have been console apps. But I'm stuck with PHP and tousands of $ signs that come with it.

    Well, I've tried a lot to separate Business Logic from Presentation Logic - but it just doesnt happen, even though each php script of mine has:
    include_once("common_funcs.php");
    right at the top.

    Though PHP aint that bad - I wish there was a better way to do stuff. Probably it's got to do with the statelessness of the HTTP protocol.

    1. Re:Can this be done?? by KDan · · Score: 1

      Yeah, you could write that in C++... Have fun! :-)

      Daniel

      --
      Carpe Diem
    2. Re:Can this be done?? by Anonymous Coward · · Score: 0

      Yeah, you could write that in C++... Have fun! :-)


      I'm pretty amused how Slashdot mod articles. How to be modded up? Beeing totally ignorant? Racist? (go check out some "Oh my God! Some dirty Indian got my Job!!!" Yeah, and those writing the articles are SysAdm, how comforting.)

      Quite often, some of the most interesting articles have very low mod points, go figure.
  22. Controller by KDan · · Score: 1

    Have you considered building yourself a controller like Jakarta Struts, in PHP? I haven't heard of one, but that might clean up your problems. With that, you can place a lot of "use this function in this page" logic in XML files so that it keeps your code clean. That would be some work, I guess, converting Struts to PHP, but not altogether undoable. You will probably need to make use of mod_rewrite.

    Daniel

    --
    Carpe Diem
    1. Re:Controller by Anonymous Coward · · Score: 0

      There is Struts for PHP, google for it.

    2. Re:Controller by oarra · · Score: 1

      This is a slight variation on the mvc paradigm. Written in php and released as gpl. Check it out... http://phrame.sourceforge.net/

  23. I second dropping PHP by Anonymous Coward · · Score: 0

    Everytime I use PHP I end up feeling dirty. Mixing the code and the presentation is just not the right thing to do. Content/View/Model is as close as I can tell to being the right thing. I personally have had great experiences with Apache PageKit and you get to use perl. In addition I'm rolling my own system using Python and Albatross. But PHP? Shudder.

  24. duh, don't put them in your public web tree by DrSkwid · · Score: 1

    that's what the include path is for

    --
    There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
  25. Page based is not scalable by DrSkwid · · Score: 1

    I use a neat Apache rewriting trick

    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*\.html$|.*/$) /index.php [T=application/x-httpd-php,L]

    that way when a request for a page that ends in .html is not in the document_root then index.php get's called instead and you can use the $_SERVER['REQUEST_URI'] to see what page was required.

    the world is an easier place when

    http://www.thebigchoice.com/Graduate_Jobs/IT_and _M anagement_Systems/York/

    is the URI instead of

    http://www.thebigchoice.com/show_jobs.php?sectio n= Graduate_Jobs&job_section=IT_and_Management_System s&area=York

    --
    There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
    1. Re:Page based is not scalable by Old+Wolf · · Score: 1

      Is it? I prefer the latter because you can put the parameters in any order. The former has the constraint that you have to define the function parameter order as well as their names. What if someone goes http://www.thebigchoice.com/York/Graduate_Jobs/IT_ and_Management_Systems/ ?

  26. SSTP by SiMac · · Score: 1

    You could try SSTP...it's a generalized layout engine written in PHP. It's very simple to work with, since it's designed for retrofitting a previous website with a layout. Just generate a simple HTML page and run it through the SSTP interpreter, which will apply the template and everything. It's not as fast as I'd like, but it works well and it has a cache if you want it.

  27. Template Systems by JonBob · · Score: 2, Insightful

    Imperator wrote:

    Use a good template system like Smarty. Just because PHP lets you mix code with HTML doesn't mean it's a good idea.

    There are some who would strongly disagree with you on this point. For some interesting arguments against templating systems written in PHP, check out this article at phpPatterns.

    1. Re:Template Systems by dismayed · · Score: 2, Informative

      As a counter to this...

      If you have to hand off your code to another person who will be doing primarily design, for instance customizing the "look and feel" then using separate templates is really valuable. You will drastically cut down on "bugs" caused by changes in the logic introduced by a designer changing code accidentally.

      Even if PHP is the templating engine, separating the logic is important.

  28. I feel you with every bit of my soul by arnorhs · · Score: 1

    I've also been programming in PHP for some time. I've developed a rather good class library which I always use. I do everything template based and all my database stuff (except writing the sql queries themselves) are object oriented.

    Even with all this, I feel I'm programming faster, but still I can't get anything architected properly. I've examined hundreds of open source PHP classes and apps (freshmeat & phpclasses), but none of them really use a good architecture.

    I'm beginning to feel like it's not possible to write well architected apps in PHP.

    I'm a very experienced delphi programmer, also, and doing good architecture is a lot easier in a non-request based development.

    Since everything always has to be loaded and parsed in each and every request, I'm beginning to feel you really CAN'T create a good structure/architecture in a request based world like php. Everything always ends up dirty (at least in some areas).

    I wish I was wrong, and I wish some of the comments above had disproved this, but they haven't. Actually, even though I don't want to start a flamewar, I really just don't think most PHP programmers know what a good architecture feels like, and that's mirrored in the way the comments above sound, even though some of them claim they have good architecture. Sorry.

    We need a good book on this subject :)

    1. Re:I feel you with every bit of my soul by Old+Wolf · · Score: 1

      You're not alone.. I love writing big projects in C, but all my PHP work seems very hacky, and when coming back to it after 2 years to make some code changes I can't understand how everything hangs together (despite lots of comments etc). Help!

  29. Binarycloud by Anonymous Coward · · Score: 0
    Maybe a framework helps..
    binarycloud is a third generation web application platform for php
  30. Use tools and frameworks by guusbosman · · Score: 1

    I'm a reasonably experienced Java developer (4 years). We're mostly creating J2EE applications at my work.

    Recently I had to work in PHP as well; a friend of mine wanted a small website. It was quite a change!

    I know Java has its drawbacks, but the tooling is becoming really good: Eclipse, code beautifiers, Javadoc, Junit, StrutsTestCases, Hibernate ... they all make developing a lot easier.

    Tooling for PHP is another matter. There are editors, there are Eclipse plugins, but nowhere near the level of Java (or, of course, Visual Studio for that matter). It seems like all the tools are just a bit less mature (perhaps with the exception of database-access layers, there are quite good ones available). A point where PHP beats Java is of course deployment: simply change the source file, reload the page, and your application is deployed. That takes a bit longer in Java ;)

    However, tooling isn't the most important thing for a good system: the design is what really matters. This is not made easier by the lack of decent OO functionality of PHP. My approach was to stick with the 'Struts-way' as much as possible.

    There's a reasonable Struts-replacement (Phrame), which works pretty neat with the template engine Smarty.

    The project worked well -- but I'm happy to be back at Java. Somehow programming in PHP felt a bit 'ugly'. Although the code is quite readable, and the application works nicely, I don't have the same proud feeling I (sometimes :)) have when writing Java code.

    Don't know if it's an option, but I saw quite decently priced Java hosting: http://www.4java.ca/ (no personal experience with them though).

  31. Core Control by devvincy · · Score: 2, Insightful

    I've been designing PHP & CGI based online applications for a while and have come to primarily focus on one way of implementing any large scale PHP project, I haven't worked on to many smaller projects so don't know if this would be a good way to go or not.

    I usually centralize the system initialization in a single file, ie index.php, system.php or core.php. This file usually performs the rudimentry stuff that all pages need, ie including config file, init database, calling authentication functions, and the basic theme display/theme stuff.

    All of this is usually controlled by a serious of ojects, one for the database, authentication, and display itself are kinda the main objects, others may be implemented depending on the project.

    After the system initializes itself and does the top level functions. The display object usually creates an object or includes a php file to handle this function. I usually have the system attempt to do this dynamicly based on a GET or POST value so modules can easily be added or removed.

    This may not always be the best way to do it but works pretty well. It really makes it easy to add top level function to the over all system and the single file or object for actually performing system action are easily updated and can all be centralized, this create a much more module system.

    --
    I hope the third little piggy got mad cow - ^_^
  32. elegent architecture? try OpenACS by gabe · · Score: 1

    I agree very much with Randolpho's post. Ditch PHP if you really want an elegent architecture. If you really need to stick with PHP, try out Midgard. Otherwise, you really ought to at least look at the alternatives. Zope and OpenACS are probably the best open source web application systems/environments/architectures, whatever you want to call it. I prefer OpenACS (there's just something about using a system that was built primarily by highly intelligent MIT and CalTech alumni...).

    OpenACS is based on AOLServer (probably the best, and first application-oriented web server out there, which was GPL'd by AOL thanks to Phil Greenspun's nagging. it's multi-threaded, it has database pooling, a healthy set of modules/plugins, and a wonderful community.), Tcl (you'll get used to it, really ;), and either Oracle or PostgreSQL. Thought it was designed for use with Oracle, and was ported to PostgreSQL, the architecture in OpenACS permits you to easily swap in support for other databases. Though, you'd have an extremely tough time getting it to work in MySQL as it relies on numerous high-end and complex relational databases features, most of which MySQL does not support.

    OpenACS is highly modular, built entirely out of smaller packages, with its own package management system. There is a core package, the ACS Kernel, ACS Tcl (which contains most of the utility code, etc.), and there are various packages built on top of that which provide both specific application functionality, but also services that other packages can use. The documentation is built into the code and is available online in every OpenACS installation. Higher up packages include web page creation, bulletin board systems, blogging, content management, etc. You can "mount" these packages at various locations in the site map for your web site / application. E.g., you could mount an instance of the bulletin board at mysite.com/forum, and add a second one at mysite.com/techsupport. You can create subsites, such as mysite.com/internal/. There is an extensive and incredibly powerful permissions system so you can completely control access to every part of your system. There is also a built-in templating system which provides a simple separation between logic and display code, as well as theming capabilities.

    I'm sure there's a lot that I've neglected to mention here. But I think you can get the point. OpenACS is a very mature platform that's be in development and production for many years now (hell, take a look at what Ars Digita was able to accomplish, they were making millions selling this system, and they gave the code away for free under the GPL). Don't take my word for it, go to the website and read about it. The only drawback to it that I see is that it does have a high learning curve. It took me a few months of reading and experimenting with it to really understand how the system works, but it's definitely worth it. There are a few hosting providers out there (Acorn Hosting and Zill.net) that offer affordable hosting packages, but it's also easy to setup your own server. OpenACS also has the ability to run multiple server boxes in a load balanced environment, so if you need to scale out, you can. Oh yeah, this is also a descendant of the same ACS system that RedHat's Enterprise Applications are descended from (RedHat got that technology when they bought the remains of ArsDigita.

    --
    Gabriel Ricard
    1. Re:elegent architecture? try OpenACS by Anonymous Coward · · Score: 0
      Oh My God! It's _not_ using MySQL!

      Just kidding :-)

      Nice article! I'll check out http://openacs.org/

      /Functorium

      PS Actullay, I'ts nice seeing PostgreSQL used instead for MySQL...

  33. Drupal by swinerd · · Score: 2, Interesting

    [disclaimer: I'm a Drupal contributor]
    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 ;) cleanliness.
    It's fast and powers sites like Kerneltrap which sometimes is on /. 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.
    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.

  34. You really want Zope... by supton · · Score: 1

    ...and Python.

    PHP4 is problematic archectecture for what you ask. PHP makes profoundly stupid architecutral blunders like lack of namespaces for library functions, which makes it hard for someone else reading your code to determine where function X came from? Inline includes.evals of code are bad, bad, bad too.

    You really want a MVC-ish sort of seperation of concerns, I suppose? Zope will do this: XHTML or XML Zope Page Templates, which are valid XML (code via attributes and XML namespaces) using the TAL namespace. Also, ZPTs will allow you to put mockup in your templates and strip out at runtime. In Zope, page templates (view) use simple Python scripts or ZSQL methods for glue logic (controller), and support either content objects developed as low-level Python Products (model) and stored in the object database, or alternately, just have content stored in every RDB you could think of. Best of all, Zope uses Python, which is a much more clean language.

    1. Re:You really want Zope... by dismayed · · Score: 1
      Just a side note... you can use ZPT's from PHP now also....

      PHPTAL --- ZPT's for PHP

      I have used all the other templating systems, Smarty, phplib, and have used templating systems in perl such as TT2 and find that ZPT's work out very well for keeping the designer happy and me as a programmer happy... Like Smarty PHPTAL is a pre-compiling templating engine, so you end up with quickly executing templates.
    2. Re:You really want Zope... by aderuwe · · Score: 1

      For an MVC architecture in PHP you should give Phrame a try. Quite cool, but there's a bug in the 2.0 release.
      Easy enough to fix yourself, but I can send you an updated version if you don't like to bother with redo-ing work.. Just reply to this if you're interested.

  35. Elegant PHP? That's tough. by togofspookware · · Score: 1

    I've been working with PHP for a while, now (not because I like the language much, but becaust it's what's available, and sometimes because it has lots of useful built-in functions :) and have come to the conclusion that YOU CAN'T WRITE ELEGANT PHP!

    I mean, first of all, how are you even going to load your libraries? Say you have a directory that contains your library of code. Call it "lib/TOGoS" (that's what mine is called). Now, say I have 'lib/TOGoS/TSDFEntrySet.php' and 'lib/TOGoS/TSDFParser.php'. TSDFEntrySet relies on TSDFParser, so it does a "require_once ('TOGoS/TSDFParser.php');" at the top. But that won't work because depending on where your script is, your library will always be in a different place! If you have access to PHP's library directory, you can put your libraries in there. But often you won't have access to that. Now you could solve this by putting in absolute paths for all your libraries (yuck) or by making a global variable that tells where the library directory is (ewww), but I've found that the most elegant (least kludgy) way to get around this particular annoyance is to CD into the 'lib' directory and require files from there (ugh). That way at least your libraries don't need to worry about it!

    I've been spoiled by Ruby and the way you can just do "$: << 'lib'" :)

    Anyway, after tearing apart and re-writing all my scripts about 3 times, I think I'm finally starting to find a way to do this that doesn't seem /quite/ so kludgy...

    <?php

    $apath_docroot = '../../';
    require_once ($apath_docroot.'main.php');
    trequire_once ($lpath_lib, 'TOGoS/WebPC/MessageBoard.php');

    $page->output_head();

    $messageboard = new TOGoS_WebPC_MessageBoard('entries/');
    $messageboa rd->load();
    $messageboard->output_page();

    $page->output_foot();

    ?>

    Which needs a bit of explaining...

    the $apath_docroot global variable is the 'apparent' (as in to the web browser) path to the document root. This is used by the $page object, for example, to write links to style sheets or the site index or whatever. My 'main.php' is kind of a site-wide configuration file. It creates the 'trequire_once' function (which 'CD's into the directory specified by the first param and requires the file specified by the second), and sets $lpath_lib (local path to lib, as opposed to apparent) and $page (an object that helps me build my pages). Now in order to do all that, it needs to know the path to document root. Usually this is the same as $apath_docroot, so it can just use that, but in case it isn't (because this directory is Aliased or whatever), I'll also specify $lpath_docroot before requiring 'main.php'.

    One problem I seem to have a lot (not necessarily a problem with PHP, but it does seem to come up more with server-side web programming) is that I choose the wrong things for objects to do. Here's a hint: It's usually a bad idea to make an object responsible for loading itself or displaying itself. When I do this I end up running into problems like subclassing a class to display itself differently, but then when I retrieve it from somewhere ($entryset->get_entry(5), for example), it'll not know anything about my subclassing and give me the original object. So it seems that the best way to go about this is to have one object whose job it is to interact with the user, and one object whose job it is to load and save data from files or from a database. When you create the front-end object, give it a reference to the backend object, and all it has to know is $backend->get_entry_list() and $backend->get_entry(id) The backend'll most likely return an associative array. And it can use a DBMS, a directory full of text files, or an XML document to store the data. The front end doesn't need to care!

    Also, note how I have a 'WebPC' subdirectory under my personal library directory. This directory contains all the code that deals with the web inter

    --
    Duct tape, XML, democracy: Not doing the job? Use more.
    1. Re:Elegant PHP? That's tough. by dismayed · · Score: 1

      Just edit your include_path using a .htaccess or by editing your site wide include_path. This way you can include your files using your syntax, require_once "MyApp/file.php"; This type of configuration is common in every other environment, so why not use it in your PHP? :)

    2. Re:Elegant PHP? That's tough. by togofspookware · · Score: 1

      Hmmm. Well the problem was that I couldn't edit the site wide include_path.

      I wasn't aware that you could put that in a .htaccess file, but I tried it and it worked and I'm rather happy about that :) Just like so:

      php_value include_path /var/www/html/lib

      As I was googling for how to do it just now I found that you can also do this:

      ini_set('include_path','../lib');

      Never knew of that function before, but it works!

      It seems to be time for me to clean up my scripts, again. :)

      --
      Duct tape, XML, democracy: Not doing the job? Use more.
    3. Re:Elegant PHP? That's tough. by myz24 · · Score: 1

      I used to find that annoying too, now I just use this trick at the top of a file

      $base_fs_path = $_SERVER[DOCUMENT_ROOT];
      require_once($base_fs_pa th . "/lib/file.php");
      require_once($base_fs_path . "/lib/other.php");

      If it's the case your app hangs off of the document root such as http://server.com/application then you would edit the $base_fs_path to be like this instead:

      $base_fs_path = $_SERVER[DOCUMENT_ROOT] . "/application";

      Now, this of course much more useful if you use a single "controlling" script from which everything starts, which has been my current favorite. For me it works like this

      Request comes in to /index.php?module=people&action=new

      This would result in something like this

      <?php // include the config // which of course defines base_fs_path
      require_once("config.inc.php");
      require_once($base_fs_path . "/modules/" . $_GET[module] . "/" . $_GET[action]);

      ?>

      This is a bit of a crude representation of what I'm doing but it works well for me. Basically results in a stack of modules and index.php creates any required global vars and finishes up the page when the require_once scripts are done.

  36. my solution by Pflipp · · Score: 1

    I have made a system which automatically stores data objects to a MySQL database. Each class gets its own table, and each subclass also gets its own (where it stores its particular data). Links between objects are presented as references to object ID's, and you can load and save any object by this ID.

    There are one or two hackish and/ or purely practical things about this solution, but you can write fast and elegant PHP code with it (which is why it was made -- I too found PHP lacking on this). The database is MySQL but a port to any other database would be possible without having to alter your scripts -- they remain database independent.

    The biggest problem with this code is its "internal" state, e.g. not being known by the world, not really being compared to other systems, and lacking support and H-Q documentation.

    But if you're interested, version 1.0 is available from here: http://pflipp.nl.eu.org/software/sssi/

    (The product is called "Achterwerk", which means "rear end". Which is why we have our (trademarked :-) slogan "Now you know where to stick your data" :-)

    --
    "We can confirm that Debian does *not* ship the version with the trojan horse. Our version predates it." [CA-2002-28]
  37. try this by holovaty · · Score: 1

    One strategy I use is to write ultra-generic PHP classes that handle generic Web interactions -- a SinglePageVisit, a OneStepValidatedTask, a TwoStepValidatedTask, etc. Those classes implement a basic logic -- e.g., the OneStepValidatedTask displays a form, then validates the user input, then either displays the form again with error messages or executes the SuccessAction.

    Then I use composition or inheritance to extend these generic concepts into specific applications. (To continue my example, the child class for OneStepValidatedTask would define what exactly SuccessAction does.)

    This approach has been useful so far.

  38. Re:Oh, the pain of Zope by Anonymous Coward · · Score: 1, Informative

    I've used Zope and PHP, and they both have their strengths and weaknesses.

    Zope's documentation is painfully, hopelessly bad. That makes difficult to move to more challenging projects.

    I love PHP's online manual. The inline comments left by other users frequently help me figure out some odd error I'm having.

    I'd go on and on here, but I'm really supposed to be paying attention to my lecture here :)

    Froggie!

  39. Re: I agree by @madeus · · Score: 1

    I agree, I've developed quite a lot in Perl, and multi-tiered functions and modules (with clear, obvious and documented pruposes) are the way to go.

    I'd never want to embed SQL/LDAP/etc calls in a page and I always cringe when I see that. I'd rather have a function:

    get_user_realname($username);

    which might call:

    db_connect();
    db_get_data(key=>'username',value =>$username,retur n=>"realname");
    db_close();
    return($realname);

    (and then I'd right db_connect, db_get_data, db_close as my own functions so I can easily change the modules I use to connect to the DB at a later date).

    This way it's much easier to do elegant error handling and to optimise code (as you can easily identify bottle necks).

    Non structured code is a maintenance nightware and something done by bad web developers who are either incompotent or would rather they look good for the boss than spend time doing something properly (and ultimately doing the Right Thing for their employer in the long run).

    It think this is one of the problems of PHP - it's easy to use, but does not enforce any structure, so those with no design knowledge (or aptitude) can get stuck in and turn out nightmare FPOS software by the bucket load. You can do this with Perl too, but ultimately I think some of the additional complexities of Perl beat this out of most users after a while and they end up being better developers in the long run (because like it or not they end up learning things).

    Ultimately however, some people are dumb-as-stump and won't ever be able to churn out sensible C/C++, Java, Perl, PHP or even VB. :(

  40. Frameworks out there. by tetranz · · Score: 1



    Phrame has already been mentioned.

    Eocene (Looks very promising)

    php.MVC

  41. check out Ariadne by Anonymous Coward · · Score: 0

    These guys did a really good job of abstraction of the various significant parts of their app. A lot went into the database, and it allows for development of other systems with out much more PHP code. Multi-language is handled nicely.

    ariadne.nuze.nl

    Also, there is typo3.org... that is another interesting bit of code that basically allows you to use the template system, and it takes care of the rest.

    --gabe

  42. Use MVC of Course! by JavaSavant · · Score: 1

    My approach to this has always been to provide a separate script that handles the logic required by a controller in an MVC methodology, but not to use include() or require(), but rather have it act alone, e.g.:

    mysite.com/control/index.php

    whereas in my apache config, the control script performs controller type logic (e.g. request parsing and handling, session initialization, parameter encapsulation, etc.) and then requires the PATH_INFO as the the model (e.g. an Action if you were using Struts). Use Smarty for your View tier, ad you have a complete MVC system.

    http://wayback.sha-bang.com for a working implementation of this idea. Essentially, the result is that you should never have to call include('control.php'), but rather all the logic in control.php should be forced by the apache configuration and the controller logic.

    Another thing I've implemented is that all of my "action" scripts have defined functions, e.g. a service() and init() function that are called by the controller script through a callback.

  43. It's not for people to read by DrSkwid · · Score: 1

    it's for machines

    url's provide a context for the content

    s'all about the page ranking

    The search parameter order randomness is not unworkable, it already does that for the last two items

    http://www.thebigchoice.com/Graduate_Jobs/York/I T_ and_Management_Systems/

    and

    http://www.thebigchoice.com/Graduate_Jobs/IT_and _M anagement_Systems/York/

    yield (almost) the same page (the url affects the H1 you see)

    --
    There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter