Going Dynamic with PHP
Five-Oh writes to tell us that IBM DeveloperWorks has an interesting article about the OO advantages of PHP V's new features. From the article: "PHP V5's new object-oriented programming features have raised the level of functionality in this popular language significantly. Learn how to use the dynamic features of PHP V5 to create objects that bend to fit your needs."
- Class constants must be string literals and only string literals (no variables, arrays or objects).
- Type-hinting is confined to arrays and objects (feature?).
The unadorned output of phpDocumentor, PHP's analog to JavaDoc, is also suboptimal; for documenting PHP, therefore, go Doxygen.I'm curious about the Differences between PHP 4 and PHP 5, can someone provide a link, or first hand info about the good and bad of PHP 5.
Programmers are responsible for implementing bend() or acquiring alcohol-fueled robots before folding objects.
From php.net
The answer would seem to be that there is no input validation or output interpretation going on in this sample. So, you can either write a switch block that makes sure your integers are in valid ranges, etc. or go back to individual properties. (Six dozen of one, half of the other.)
It's a huge step forward for OO development in PHP.
BUT it's still got all the crud of PHP4. For those transitioning from PHP4 objects one great feature is the new warning when using the older style of classes. However all of those things people find quirky about PHP4 still exist. For example, now you can force a function parameter to be a certain type of object, but not a basic type. You still can't even fully overload a function.
My view is that it's two steps forward and one step back. They need to consider deprecating features and making a php.ini option to not allow the use of any deprecated features.
Developers: We can use your help.
PHP: The Language For People Who Can't Code Perl
This page actually has alot of links of changes and new features. What's New
-- Brought to you by Carl's JR
There's a good summary on Zend: http://www.zend.com/php5/andi-book-excerpt.php
Basically, PHP 5 adds proper object support (think Java-style) including iterators for objects, and new extensions add good XML support, SOAP, SQLite, better MySQL support (prepared statements, OO interface, etc.)
I'd recommend reading Adam Trachtenberg's book Upgrading to PHP 5 if you're familiar with PHP 4.
If you think those look similar, I can't begin to imagine your opinion of every company's logo for the last six years.
I'm a fan of using objects in the right place .. but to suggest they increase the functionality of a language is simply wrong. They allow for better (well, different) organisation of code, easier reuse, and improved encapsulation over procedural or functional coding styles, but they don't actually allow you to do anything that can't be done using any other approach. The functionality of the language remains the same.
http://twitter.com/onion2k
I'd love to take advantage of some of the PHP5 features. However, most hosting services are still stuck on PHP4. How long has it been now? I am the project manager for WebCalendar, and just like during the transition from PHP3 to PHP4, it's going to be some time before we can drop "legacy" support for PHP4 and take advantage of the cool new features of PHP5. So, for now, WebCalendar and other open source apps will have to stick to PHP4.= rss1
FYI.... PHP developer articles updated daily:
http://www.devpointer.net/browse.php?l=p&t1=1
RSS:
http://www.devpointer.net/browse.php?l=p&t1=1&fmt
http://www.k5n.us
Linux is NOT backwards compatible.
This is what I was thinking the entire time I was reading the article. I mean, it's one thing to have to whip up some small project for yourself, it's another to build a project that is maintainable by a group of people.
I'd bet that Brian W. Kernighan and Rob Pike (The Practice of Programming) would probably recommend against using it. It doesn't provide for clarity, nor does it simplify, it just makes things "easier" for the guy that writes the original code.
Notes From Under *nix: blas.phemo.us
Once you get to know a couple of other programming languages, PHP and Perl look quite similar indeed. (Kind of like VBS and ASP, Java and C#, C and C++, etc. are similar.)
Okay, back to nerding.
You can have my one-button mouse when you pry it from my cold, dead fingers.
PHP5's object are passed via reference by default. Public/Private function and variables in classes are also now supported. The language as a whole has better OOP support and the underlying engine is alot faster as well.
Also, some deprecated functionallity has finally been dropped. All in all, I've been using PHP5 for awhile now and everything works alot faster as a whole (as I use it with Apache 2 as well).
One note that might concern you, PHP5 does not come with MySQL built in anymore. You either have to download the update or compile it yourself. It's nice for those who want to use something aside from MySQL and don't want to have to keep it the module loaded constantly but it's also a pain for the beginner hobbyist who has never had to deal with installing the MySQL module for PHP.
This is my sig. There are many like it but this one is mine.
So, it's got some of the features of Ruby now, plus a whole lot of crap dragged in from PHP 3 and 4 inluding that crazy mishmash of a function library? Boy, sign me up.
"welcome to 1967".
http://en.wikipedia.org/wiki/Simula
Y
Here are two other approaches to consider:
1. Use maps (associative arrays) instead of objects. If it is mostly just attributes, then the difference will be small. Map syntax is usually more compact than object syntax, keeping the code clean.
2. Create a data dictionary table where field attributes and even code or function calls (used with eval() function) are kept. However, you will need to find a good table browser to enter all that conveniently. A data dict table may not always be the most efficient from a machine standpoint, but can make for good RAD if used well.
Table-ized A.I.
I've clicked to another tab to browse at some other site and then I've seen suddently:
...as the title of the Slashdot tab. It gave me the creeps until I remembered whats the article about. Phew.
"Slashdot | Going Dynamic with PHP"
It takes a man to suffer ignorance and smile
Be yourself no matter what they say
Any fool can code Perl, just like any fool can code PHP/C/Java/VB/Smalltalk/COBOL etc. etc.
Anyone can write code, but very few can write really great code, that reduces the problem to the essential elements and uses the simplest approach to the problem, with the tool (i.e. language) in hand.
You can write shit code in ANY language. You can also write good code in ANY language (within the limitations of the language).
What you're saying is like "Spanish for People who can't speak in German".
It's nonsense and insulting at the same time.
You need to express yourself or solve the problem within the framework of the language you have.
You might choose a different language for a particular task, but if the language is a given, a good poet (or programmer) will make the best of it.
A better language doesn't make one a better programmer (or poet).
Comments that a friend made: PHP 5 -- when using the OO -- looks a lot like Java, except no real threads, no security (sandbox), no WeakReferences and other GC niceties. Enjoy!
Perl is another alternative, and admittedly a pretty popular installation (I imagine anywhere that offers PHP hosting also offers Perl) -- but for someone like me who wants to do the occasional scripting the language is not exactly ideal -- nor is it especially easy to read someone else's code. I think Perl developers are incidentally the most "guilty" party of poorly commented code in FOSS projects, which doesn't help matters.
As a designer and occasional scripter I was interested in learning more PHP at one time, but now I feel as though it's a bit of a dead end, especially for "bigger" projects. Learning Python seems to be time better spent at this point; I can run a native interpreter as well as Java and .net based interpreters to handle more "enterprise-sized" projects; Python has a stronger OO foundation than PHP in existing versions, is designed to easily integrate with C modules, and reads easily. It's also shown itself to be equal to a broad spectrum of applications from commercial tax forms software (QuickTax) to web application frameworks (Zope) to HTPC frontends (Freevo) to P2P software (BitTorrent).
As for PHP, roll me over when version 5 is standard across the board and I'll consider taking another look at it.
Linking some form of programming and variable naming convention would have been nice, too. He doesn't have to go into detail, just lay mention to it. Something like "Just fyi, I follow X conventions when naming my classes, variables, etc..."
Then you tack on the complete lack of comments! ^_^
For the beginner/hobbyist I found LAMPP, more specifically XAMPP, to be very easy to use. The newest version came with PHP5 and mysql 4.1 (i think). It installs in minutes and works on linux and windows.
There is an implementation of this idea (and more) in PEAR's DB_DataObject package:
- dataobject.php
http://pear.php.net/manual/en/package.database.db
That CD PHP Logo looks a lot like the Nike Swash to me.
I was following PHP5 development until the RC1 deployment, and I was disappointed. There wasn't really much, I yearned for a new, truly OO language. Luckily, about the same time, Ruby on Rails was getting a lot of attention and I checked that out, now I couldn't be happier. I do some contract work in PHP4 and PHP5 sometimes, and I just get this sick feeling. Honestly I'd much rather program in Perl than PHP.
Combining the dynamic getters and setters with the PEAR DB_Table (http://wiki.ciaweb.net/yawiki/index.php?area=DB_T able) class would truly kick ass - full run-time definition of tables, HTML_QuickForms, and all that other whiz-bang stuff. No more .sql scripts anywhere, hell, no more SQL anywhere!
Can RoR do that? (Honest question, I'm a PHP guy, but have heard a lot about RoR)
DB_Table is worth checking out.
...but PHP does not force object orientation - you can still write all the sloppy RAD procedural non-variable-verifying web-code you want with PHP! Sure, you can still write sloppy Java code, but PHP does NOT have the enterprise integration, security or advanced language features of Java or *gasp* C#.
Horns are really just a broken halo.
Comment removed based on user account deletion
The one thing I was disappointed about this article is that it doesn't make a "describe $table" call to get the fields for you. You could then extend DBObject to like DBO_customer and the constructor would yank "customer" out of the class name. So then all you really have to do is extend and rename and that's it. No need to directly pass the table name to the constructor.
Secondly, by modifying the load function to accept an array of id's and implementing the Iterator interface, one can use the object in a foreach loop to iterate over each customer (perhaps by implementing DBObject::current() to instantiating a new object and populating it with data for a specific customer thus maintaining objects within the foreach loop). (The trick is to tie the original object into the new one so a data update in the new object is reflected back to the original.) Maybe even add in transaction support on update & delete calls.
Thirdly, if you add in "dirty" and "new" flags to each row stored in the object then you can combine insert, update, & delete calls in a single DBObject::sync() call (again wrapped in a transaction if you wish).
Fourthly, don't forget __unset() and __isset() to remove or check for fields.
Fifthly, store the other columns from the describe call and do validation and/or type conversion automatically.
Finally, __sleep() and __wakeup() would be useful for serializing objects to a session or something. That one's easy though: just serialize() your fields array and unserialize on wakeup.
One more difficult step I have yet to try is supporting joins (perhaps you want to load an object with a customer and all of their orders) which would save the need to use 2+ objects.
:wq
While the approach in the article does appear to be quite good for rapid code generation, I personally wouldn't touch it with a ten foot pole if I had a choice, though I was unfortunate enough to have to work with such a setup recently.
The problem with this kind of setup is that while it works well for simple work, the moment you try and do something more complex, you'll find you have to fight against the API, and the code will end up being a mess in order to do a task that should be quite simple.
Naturally I have a somewhat different approach that's somewhat weird, but I've enjoyed great success when using it. I have one database object called 'database' funnily enough ;) Inside this database object there are four other objects, select, insert, update & delete. Now, each of these four objects aren't anything special, they're simply wrappers around methods of a particular type (select queries go into select for example).
To give an example, where the author in the example wrote
I would simply write
This method will return a result object, from which I can retrieve the id simply by typing
Now how does the internals of this work? I won't say, simply because it doesn't actually matter, which is the whole point of this kind of setup. It provides a very simple API, so that in the back I can make it work however I want, allowing me to easily switch in different databases, or if I wanted to I could make it work with flat text files. This way I keep all my messy SQL contained in one area and I don't see it anywhere else, making it much easier and cleaner than the method offered in the article. However, my method will require more work to setup initially, and naturally it won't automatically adapt to changing database tables... though I have to wonder about the quality of a project wherein the tables are changing frequently, that's the kind of thing one should have planned out from the beginning.
That said, I'm sure there is some value in setups like the one mentioned in the article, and my own database abstraction code is hardly perfect as I'm still something of a beginner at programming in many ways.
All I wanted was a simple and effective tool for iterating over a directory of files (recursively), and looking for content that matches the argument...
No, wait...
All I wanted was an obtuse, terse, un-commented, obfuscated, half-mile-long script that uses one-letter variables, one-letter function names, has 87 module dependencies, and can only be run in one version of perl compiled by a Hungarian from Walla-Walla Washington on an 8086 running DOS 1.0 on Tuesday, March 3, 2001 at 0413 GMT -6... preferably with the entire script written in one line of code with no extra white space and has no wrapping to fit a little term window...
No, wait...
Your comment is true, but the same can be said about Perl (it just sounded like you were putting down PHP only).
PHP 5 does indeed have more "complete" support for object orientation. The new XML/SOAP libraries are also a welcome addition.
However, IMHO it is still lacking one crucial feature - application scope for variables. Most of the competing platforms (ASP, JSP etc) allow a website to operate with shared memory (between sessions), but in PHP this is a glaring omission.
Try creating an AJAX chatroom in PHP. You'll find yourself stuck between a rock and a hard place - either messing around with cumbersome file I/O or hammering the DB with lots of connections and requests.
Now try it in JSP, for example - simply put a couple of objects into application shared memory and the task is accomplished elegantly.
I love coding PHP but I miss application scope.
This is what frameworks are for. Security and performance conscious people like myself write them so that other neophytes and developers alike can make good PHP apps without worrying about those things.
'Yes, firefox is indeed greater than women. Can women block pops up for you? No. Can Firefox show you naked women? Yes.'
PHP: Polish Howling Perfect
PHP: Polish Heavy Perfect
PHP: Prostitute Hard Powerful
PHP: Putty Hypertext Preprocessor
PHP: Purr Hobo Prostitute
PHP: Protection Hairy Poop
PHP: Puntme Homosexual Puntme
PHP: Polish Homo Pimp
PHP: Poop Hot Protocol
PHP: Purr Homeland Pipebomb
PHP: Protection Hot Programmer
PHP: Pope Hypertext Perfect
PHP: Prostitute Hoard Protection
PHP: Piles Hypertext Protocol
PHP: Pooping Hard Powerbook
PHP: Pimp Huge Php
PHP: Powerbook Horrible Piles
PHP: Poop Howling Pope
PHP: Protection Homeland Powerful
PHP: Pipebomb Hitler Plop
LISP, bitches!
PHP5 uses MySQLi which has both a procedural and object-oriented interface, and it supports features from MySQL 4 and 5 such as transactions and stored procedures. The old MySQL libraries are technically for MySQL 3, so there's not much need for those anymore.
Then there are PHP Data Objects for a unified database interface (although it is a bit primitive when compared to PEAR DB and other DBIs).
'Yes, firefox is indeed greater than women. Can women block pops up for you? No. Can Firefox show you naked women? Yes.'
I've almost never seen OO been put to good use with PHP. It's used exclusively as a tool for the developer to write, as the author puts it, "more maintainable code". However, with the (lack of) real complexity and sprawling code bases which accounts for most web sites, it just adds complexity by adding a "system" for the developer.
Forgetting the developer, it adds nothing, and has a major impact on speed and memory. It adds nothing as in 99,9% of the times I've seen it used, it's 1) stateless and 2) a collection of single object instances (one page, one database connection, one user, etc.).
In a lot of cases, I think the programmers would have been a lot better of just seperating the logic in functions and few files, and then he can understand his own code after a few months off it.
I wouldn't characterize the object support as "proper", as it is missing some key features, like multiple inheritance and namespaces.
that actually thought it was a well done article?
/.
Seems a bit better than some of the journalist's moronic rantings that I've seen lately on
Good food for thought, good examples, good examples of the new functions that replace some of the fubar functions in 3 & 4.
Who is this that even the wind and the waves obey Him? Surely this computer must submit also!
LISP, bitches!
I'll give you some advice. If you love Lisp so much, find a better way of selling it. Lisper's have done a horrible job of convincing others why it is so great.
May I suggest writing a publicly viewable sample application that is fairly practical, not lab toys or programming contest entries; and then compare it to implimentations in non-Lisp languages and describe in detail why it is better.
For example, a college grade and course tracking system.
Table-ized A.I.
i love php5
recently upgraded my servers to php5.1.2 and mysql5 running on apache2
all my sites are programmed in OO php5 (i know it aint as good as java, but it does the job)
the speed increase has been phenomenal (i think mainly to php5 using references instead of passing by value)
i have a forum with 200 people on at any time with the server load barely above 1.0!! thats a celeron server as well!
Now that PHP is as complex as Java, it's time to move on...
Well... that was funny I must say. But being a brazilian, a native portuguese speaker, I somehow feel offended by this kind of post (I even checked if the story category was english gramatics or something). I don't feel obligated to speak english perfectly when most americans also can't do it. But maybe I'm just over reacting...
Not enforcing Object Oriented programming is actually a very good thing, one of the few good things in PHP5.
Giving the option to use OOP (with a good object system, which PHP doesn't have) is good, forcing it on the poor user and preventing him to write as much as a line of code outside of a damn class is stupid, and is a god damn failure of both Java and C#.
While OOP is a good idea for some problem, others are better solved using more imperative or functional styles. That's why I much prefer Ruby or Python to Java: while they have great object models, they don't try to beat you with an ugly stick if you don't wrap every damn thing in a useless class that is only here because the language absolutely forbids you from doing otherwise.
"The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
You mean kinda like every language that supports OO design? None of this is even remotely ruby specific, or even ruby inspired.
Yeah, yer right, PHP5 doesn't force that New Age, Gay-Arsed stuff on you.
Although, I still can't find a decent set of classes to generate cross-database SQL queries. Anything I've found has been way too bloated (e.g. integration with a bazillion PEAR classes, extending classes to make actual objects, etc), and the closest thing I've found so far is something I wrote in the first place, so it looks like I'm screwed here...
'Yes, firefox is indeed greater than women. Can women block pops up for you? No. Can Firefox show you naked women? Yes.'
An OO interface to MySQL? Can you elaborate, as I've never seen this mentioned anywhere.
With the MySQLi extension (the 'i' stands for improved) you basically call methods on/read properties of a mysqli object rather than passing a resource to procedural functions, get a mysqli_stmt object when you prepare a statement, get a mysqli_result object back from a query, etc. It's clearer and neater than the old way and it opens up opportunities for using some of the newer features like iterators.
Sorry if it sounded like I meant that it does schema-reading magic and presents your tables to you as objects or something (although I don't doubt that there's code out there somewhere that does it, and it'd be very doable by implementing appropriate _get, _set and _call methods on your particular object. Look at the SOAP extension for an example of that sort of thing.)
Let's see how it can be done better:
you would live to see IBM become "hip" again in terms of technology? I can remember when they were the MS of the computer world - evil empire, monolithic - all that good stuff. Now they are like the mythic figure of Richard the Lionheart - ready to ride in and assist the open source Robin Hood.
CodeoRowboy
"The speed of light is faster than the speed of sound. That is why some people appear bright until you hear them speak."
My firm is a fairly big fan of WASP (http://wasp.sourceforge.net/). Check it out.
The third solution, which I cover in this article, is to write a single class that dynamically molds itself at runtime to the fields of a given table. This class may perform a bit more slowly than its table-specific counterpart, but it saves me from having to write a lot of code. This solution is particularly beneficial at the start of a project, where tables and fields are changing constantly, and keeping up with rapid changes is crucial.
OK bro so I am a kitschy Perl programmer who loves invoking "Laziness" but this is TOOOOO much.
Now you can write code that is twice as shitty in half the time! And that's a feature?!?
Comment removed based on user account deletion
I look at the php executable much like I look at my kernel. How much crap is in there that I don't need.
.. hmm better grab some curl.
.. so I have the luxury of enjoying what it does and not really missing what it doesn't. But it has some uses I didn't see mentioned, so I mentioned :)
Remember,
#!/bin/bash
can also be
#!/path/to/php -q
Given all of the ways you can build php you can achieve a really nice object oriented feature filled shell script (very useful to tear through logs with regex / etc) that has an executable about 1mb in size (that was php4 I haven't really ripped apart php5).
Build php like your going shopping for car parts. Hmm ok I need sockets, gd, zlib
I have 4 or 5 jobs running with 4 or 5 different versions of php. Perl was easier and is modular but the resulting footprint is much bigger.
This is very useful when you're trying to build something into a single board computer, or where you need to run something very often that parses a lot of text.. lots of good uses.
I (personally) don't use it yet for much else. My biggest hip hip horray about php5 is support for sqlite. But I plan to use that in php shell scripts anyway.
I dont eat breathe and live PHP
While the fact you can now program in OO that hasn't really swayed my decision to move to 5 at all - what, am I going to rewrite all of my existing pages? Or rewrite functions I have ready to copy & paste when I next need them? Probably not.
The main reason I upgraded some of my sites to 5 was the addition of the imagefilter() function. I can now insert text using a ttf font in gray, use imagefilter() to gaussian blur the text a little and then add the new bit of text 'above' it to create nice drop shadowed text images on the fly - useful for dynamic sites.
Time is an illusion. Lunchtime doubly so. - Douglas Adams
Or #!/path/to/python, or #!/path/to/ruby. Your point?
"The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
Don't forget PDO in v5.1. It's a _GREAT_ feature, really simplifying database functionality for PostgreSQL, MySQL and others. The calls and itterators are really smart, and syntax is golden. It makes heavy use of exceptions. See http://www.php.net/pdo for more details and examples.
when you see the word 'Linux', drink!
propel, a pear package http://propel.tigris.org/ does exactly that.
If you love Lisp so much, find a better way of selling it.
:)
It's called Emacs.
There are three types of programmers: DevStudio/Xcode/Eclipse slaves, the above-average VI underachiver types and the Emacs intellectual porn stars
Now, back to creating Lisp modules so I can avoid Xcode and still create Universal Binaries.
Actually, to get real specific, if you aren't doing anything too heavy just realize that you have to downgrade from public and pivate class variable creation to generic creat.
So. Just do a word filter for "private" and "public" and change them to "var".
This week I started experimenting with PHP and mysql. To my shock, horror and dismay, I found out that my ISP isn't running the latest of either. This means that all the common examples fail spectacularly. Rhetorical question: that good are new features in PHP 5 and mysql 5 if you can't use them?
Unfortunately it appears that "most" ISPs (note the quotes -- this is a made up figure based on my own experience) have no plans of upgrading past PHP 4.3.x and mysql 4.0.x anytime soon.
One of my gripe here is with the mentality that it's okay to release a new major version of an interpreter without renaming the language. We've seen this with Java (most users are stuck at or below 1.4, but most web stuff requires 1.5 or higher) and perl (though to be fair, they haven't released perl6 yet so they still have a chance to rename it to avoid confusion).
Another thing that bothers me about PHP is the fact that there are so many configuration options that you have to implictly depend upon. If someone changes one of these behind your back, your scripts will start misbehaving in odd ways. To make matters worse, dozens of the defaults change from one version of PHP to the next (even between minor versions).
But it's a love/hate relationship so far. I really do like the ease of use: just write some HTML and slap in a oneliner to import some code at the right spot. However, it annoys me that it's so difficult to make anything even half way robust.