ASP.NET MVC Model binding in PHP?

I’ve been working a lot this year with ASP.NET MVC 3 and C#. One of the things I really like about these technologies is the model binding. Let’s say I have a data model called “User”, a plain old C# class like this:

I can set that as a model for my view to use in the “Edit” controller like so:

And then I have “User” as the data model in my view. Here’s what’s awesome about it, let’s say I need to accept edits of the user account, maybe they can fix their first or last name. I can pass that same User model from the previous page via a form into an Edit method that accepts that data model. I don’t have to muck about with assigning the Request variables ( POST / GET ) to an object. All that is handled for me.

The ASP.NET MVC model binding will attempt to bind your model in these scenarios:

  • If you have a form element on the page with an identical name to a property in the model
  • If the url contains a key value pair from your routing that is identical to a property in the model
  • If any REQUEST element has a name that is identical to a property in the model
  • Otherwise, that property of the model will remain null

Plus, the ASP.NET MVC model binding will let you turn on/off model binding for various properties of the model.

PHP, or rightly, the many PHP frameworks really need to implement something like this. A few perform some pieces of this concept but I’m not aware of any that currently serve up the whole enchilada. What do you think?

Continue reading

How to find all the distinct PHP session variables that your applications uses.

The short answer is a one line Linux shell command:

This command:

  • looks through all the files in your application recursively for the PHP $_SESSION reference
  • finds any variables named with capital letters, or lowercase letters, or underscores, or numbers
  • sorts the list alphabetically
  • removes the duplicate items in the list

The long answer is that I found myself with an interesting dilemma recently. How to find all the PHP session variables set in my application. Some pieces of the application were new code, some were older legacy code. I needed to get the full list of session variables because I needed to delete most, but not all of them for a certain usage case ( ie, the user is still logged in and has some properties, but the other session data could be safely destroyed ).

So I began with some command line greps on linux. First I tried:

This was a decent list, but about 1000 rows long. Too unwieldy to deal with. Let’s get rid of the filenames, I don’t really care where the session values are set for my case.

This is a little better, but I don’t need the whole line, just the session variable itself. Let’s see if we can start to grab the session var using a regex pattern.

Now we are cooking. This is a nice list of the session variables ( albeit only one array level deep which is all I needed ). Now how to remove the duplicates? Maybe we should “sort” them first?

That is really close. Is there a way to remove duplicates with the “sort” command? Yes, there is. Hot dog.

There it is. That’s the final command I used which located around 50 variables in the old legacy code and new modular code that were used in the sessions. The only really drawback to this code is it will not find multiple nested array values on the session itself, but you could add that as a separate regex if you need.

Continue reading

Explode a string with no delimiter in PHP

I needed a way to split a string by the character and put the results in an array. Sounds like the perfect job for the explode function right? Well, according to the manual:

If delimiter is an empty string (“”), explode() will return FALSE

That’s a bummer.

I also tried str_split(‘whatever’) but that has some problems with foreign strings. But we can do something like this:

Enjoy! Let me know what other ways you can come up with to do something similar.

Continue reading

SQLSTATE[HY000]: General error: could not call class constructor

SQLSTATE[HY000]: General error: could not call class constructor

This rather vague error message has been popping up in some of my integration tests lately. It’s a PHP error in PDO querying MySQL that happens when you’re using the setFetchMode method of the PDOStatement. If you use the fetchMode of “FETCH_CLASS” you can get this error in one of three ways:

  • The class you specified has not been included/required so when PDO gets results, it cannot create an object of the class you specified since it doesn’t have that class definition.
  • Properties on the class you specified have been marked as protected or private and there aren’t any setters for them so PDO can’t set the properties on the new object.
  • You used the optional third argument “ctorargs” to give constructor arguments on your new object however your arguments are incorrect and don’t match those on the class.

Hope this helps other poor souls out there trying to figure this error out.

Continue reading

Export from WordPress blog and Import to Blogger

This script exports your posts and categories from your locally hosted WordPress blog and imports them into a new Blogger blog online. The script is based on the Blogger examples for working with PHP and blog data.

Code to export from hosted WordPress blog and import to Blogger at github

You need to have the Zend Framework up and running on your system as it contains all the GData libraries for working with Google data in PHP. This script doesn’t use any of the MVC, so you just need to have the files somewhere that you can require them.

You need to edit line 8 to point to the path of your Zend Framework. You also need to update the database connection variables right below that to match your wordpress blog.

Some caveats:

  • Blogger can only import 50 blog posts per day before tripping some anti-spam protection. So the SQL “limit” clause around line 322 will need to be adjusted. It is set to get the first 50 posts and publish them.
  • WordPress “categories” become Blogger “labels”
  • Blogger forces any imported comments to the blog posts to originate from you, the author, of the blog. So I have omitted these from my script, figuring it would look crazy to be talking to myself. You could hack this script to add those back in.

What’s great about Blogger is that you can create a new test blog and run this script, which allows you to select which Blogger blog you wish to update and go from there.

The usage is:

php xfer_to_blogger.php –user=email@email.com –pass=password

The email and password here are the ones you used in setting up your Blogger account. Let me know how you make out and if you have any suggestions for the code.

Continue reading

Hiring PHP5 Programmers

My company has placed an ad looking for more PHP5 programmers to work mostly in the social networking area. We have a coding test that we give to everyone whose resume passes muster. It’s a basic test, includes some CRUD database functions as well as creating a basic Facebook app. We specify PHP5 all over the place.

But no one who takes the test ever uses any of PHP5’s attributes. Not one test app has come back using classes of any kind other then the Facebook reference.

Am I being too hard on people for this? Maybe we need to specify that creating classes is recommended if not mandatory? I don’t know what the answer is, but I know that upon receiving several recent test apps in “PHP5” that have include files that contain only functions, I’m a little depressed. And yes, I used the quotes around php5 on purpose.

Continue reading

Development Environment layout using Linux, Apache, PHP, and Subversion

Some of the age old questions I face lately are:

  • What’s for dinner?
  • Should I accept that friend request on Facebook for the friend of a friend of a friend that I knew 15 years ago?
  • What’s the best development and test environment layouts for PHP using Apache as a web server with Subversion for version control for multiple developers?

Some of you may be asking yourselves the same questions. The choice of dinner is a personal one. I won’t go into that except to say that everyone loves a good burrito. Spicy! And you probably don’t care about my take on Facebook etiquette since your friends list probably dwarfs mine.

But I do have some definite thoughts on the layout of development environments. And I find that there’s a huge lack of information about this on the interweb, so here you go.

We use Linux, Apache, PHP, and subversion in our development environment and so these instructions will be biased towards these topics but I think you can apply this method using various other technologies.

I like to give each developer their own development web site and development database. I find it’s easier for everyone to have their own individual sandbox to play in. We give them each their own domain using their initials, something like rzdev.domain.com for me, Rich Zygler, and vbdev.domain.com for another developer, Vinny Bagadonuts. We set the Apache directories up on the Linux dev box in a similar fashion:

/var/www/rzdev.domain.com/
/var/www/vbdev.domain.com/

This has a few benefits. If I need to show Vinny something with my site development, I can just send him the link to http://rzdev.domain.com/broken-page. I can make changes to code, even major infrastructure code and not break anything for the other developers. We do the same thing with the databases, prefacing them with our initials.

Now, since our dev boxes use Linux, we set up Samba for sharing on these web directories. This means that all the devs can edit files and use source code management on the Linux server itself or on their Windows machines (we use either Eclipse or Zend Studio and create projects on the shares, that’s a whole different posting!).

This dev site layout is closely linked to the way we use Subversion for version control. When we start a new site or application, if we can split out the development evenly enough, we’ll just have everyone work from the trunk version of the code, with each developer working on their own little section. Each developer puts the trunk in their Apache dir and we edit the Apache configs to reflect this:

/var/www/rzdev.domain.com/trunk/
/var/www/vbdev.domain.com/trunk/

The root of the dev sites typically look like this:

/var/www/rzdev.domain.com/trunk/docs ( your Apache document root )
/var/www/rzdev.domain.com/trunk/lib ( non-public PHP library code )

When we commit code changes in Subversion, we have a hook that updates our main development site here:

/var/www/dev.domain.com/trunk

Again, that site can be seen on the web at http://dev.domain.com/ This way, we can do integration testing on our code to make sure our new code doesn’t break code from someone else within the dev site.

Now, the important thing here is that the Quality Assurance (QA) and Testing people ( if you’re lucky enough to have them ), don’t use any of these previously mentioned sites for their testing. Why not? Well, because if they’re doing a good job and are therefore sufficiently anal, they’re going to complain when code is changing on the site they’re looking at.

So we give them their own test site and database that’s viewed on the web at http://test.domain.com/ and setup in apache at:

/var/www/test.domain.com/trunk/docs
/var/www/test.domain.com/trunk/lib

The developers will meet and create the list of files and database changes that get moved over to the test site. How the actual moving is done doesn’t really matter. If you have the time and energy to set up some Ant or Phing tasks, that works great. But copying/rsyncing files and running some SQL on the test database works just as well. The most important part is that the developers meet to decide which part can go to test. Otherwise, you could have code going to test and eventually production that might not be fully vetted.

When QA finds bugs in test.domain.com, they can send them to the developers. The developers can instantly start working on fixing the bugs in their own dev space at rzdev.domain.com and not affect the other developers or the ongoing testing of the application. Pretty nice right?

Advantages of this approach

  • Uses source code management
  • Developers can unit test their own code
  • Developers can do integration testing between each other’s code
  • Developer A typically doesn’t destroy code or data that developer B is using
  • Developers don’t destroy code or data that QA/testing is looking at
  • Developers can both edit files and use source code management in either Linux or Windows environment
  • Very scalable. Adding new developers into the mix is as simple as adding their respective sub domains and databases (of course, this can also be viewed as a disadvantage, see below)
  • Less bugs make it to production

Disadvantages

  • Lots of sysadmin overhead initially and with each subsequent domain added. You have to set up all those developer sites, rzdev, vbdev, etc. Same overhead when using branching within subversion. Plus, you have to setup all those databases and setup the config code to connect to the appropriate database for each developer domain.
  • Lots of file space for all the sites and databases.
  • Confusing for lone wolf and gunslinger developers who are used to overwriting production or each other’s development code (too bad for them!)

So what do you think? How do you setup YOUR PHP development environment?

Continue reading

Beware the Lone Wolf PHP Developer

With all the posts on interviewing PHP candidates popping up lately, I thought I’d post this draft that I’ve been sitting on for awhile that’s related to new jobs and interviewing candidates.

I’ve run into the Lone Wolf PHP Developer at several places I have done work. Sometimes, I’ve had to work side-by-side with the Lone Wolf. Other times, I’ve replaced the Lone Wolf who had moved on to different hunting grounds. Still other times I’ve had to hire people and had to choose between a Lone Wolf and several other candidates.

Just who is this Lone Wolf and why should we fear them so much? Here are some telltale signs of the Lone Wolf PHP Developer:

  1. The Lone Wolf doesn’t understand how to work in a team of developers. They typically don’t even understand what benefits that would create. They do all development on their own, listening to very little input from qualified sources.
  2. The Lone Wolf got to page 141 on Enter-A-Beginner-PHP-Book-Title-Here and no further. Objects? They’ve never heard of them. They must not need them.
  3. The Lone Wolf re-invents the wheel for every project and doesn’t use standard tools and practices.
  4. The Lone Wolf eats their young. OK, I made that one up. Frankly, how could a Lone Wolf have young anyway?
  5. The Lone Wolf is perfectly satisfied with doing programming work on production servers and using FTP to deploy their code. It never occurs to them that they should strive to create development and test environments. It never occurs to them that deployment via FTP doesn’t scale higher then one developer.
  6. The Lone Wolf doesn’t know what the letters SCM, CVS, or SVN are, or how to use them in their daily work.
  7. The Lone Wolf never reads my blog or any other blogs on programming. The Lone Wolf may not know what a blog is.
  8. The Lone Wolf says crazy things like “MySQL can’t do transactions” and somehow gets management to believe them.
  9. The Lone Wolf was initially adored by management because they launched a lot of code live during their short stay. Too bad all that code is buggy and completely un-maintainable moving forward. Management doesn’t like that.
  10. The Lone Wolf whips up incredibly stupid and unnecessarily complex solutions like template systems in which the templates are stored in a database instead of the file system/memory/cache. They shun using tried and true templating methods like PHP files, XSLT, or at the very least, Smarty. (see also: reinventing the wheel)
  11. The Lone Wolf names variables after themselves that mean nothing to anyone else (ex, $lonewolfFlag )
  12. And worst of all… The Lone Wolf PHP Developer fails to realize that there are other developers out there in the business world, trying to earn a living just like they are. By failing to conform to development standards that have been proven and tested, they make everyone’s job more difficult.

Now, I personally have run into this Lone Wolf scenario with other programming languages as well. But I think because it is so simple to work with PHP without much formal training that it lends itself to this problem much more readily then other languages. The blessing and curse of PHP is that it is the new VB 6.

Continue reading

PHP Developer Jobs are the Hottest EVER!!!

** I’ll preface this by saying that I’m not specifically looking for a new position but I think it is important to be aware of the market that you serve. Even in happy times during my employment, I routinely scan job ads to see the health of the market and to gauge its direction. **

If anecdotal evidence means anything, and sometimes it does… and at the risk of sounding like a teenage girl writing on a myspace page, the PHP job market is literally blasting off! I’ve never seen the market for PHP programmers as strong as it right now in the NYC/Philadelphia region.

While there are lots of PHP jobs in the usual suspects like small start-ups, there also seem to be a number of jobs at established companies and developer shops. I’m also seeing a definite split in PHP jobs where there are both entry level jobs as well as jobs for more experienced people with titles like “Senior PHP Developer” and “PHP Tech Lead.” I can’t remember seeing so many senior PHP positions. The salaries I’m seeing are also at an all time high. Many ads have salary ranges that extend well into 6 figures.

As far as requirements I have seen, there definitely seems to be a shift towards frameworks like Symfony and Zend Framework as well as items specifically mentioning IDEs like Eclipse and Zend Studio. However, I rarely see mention of source code management and unit testing. Hopefully those items were cut from the job ads due to space requirements. 😉

If you are a PHP developer in the area and are highly experienced, get ready to reap the rewards for your hard work. If you are a hiring manager in the area, prepare to shell out more for top talent.

So what is everyone else seeing in their area with regards to PHP developer jobs?

Continue reading