Wednesday, November 21, 2012

RedBeanPHP an amazing ORM

I want to share a little bit about my experience with a library called RedBeanPHP, since it's been a completely transformational tool for me in the prototyping process (and in fact, was a big contributor to the app that my teammate and I built at AngelHack NY, which we ended up winning).

So, here's the general idea.  In the prototyping process, no matter how much you plan ahead, it's fairly likely that you will want to add a DB column or change the values you were planning on storing.  This generally means having to do a few things:

  • Add a script to alter the existing schema
  • Make changes to a central script that builds your DB from scratch (in case you need to recreate it on a new DB instance).
  • Deal with backwards compatibility/consistency issues
When you're prototyping, this is incredibly distracting and annoying (especially if you are like me and you just want to push a version out to start measuring usage).  Enter RedBean.  Redbean is an ORM just like any other with a little trick up its sleeve- it alters the schema to accommodate whatever values you want to assign to a given object type on the fly.  So let's take the following examples:
  • Let's say I set foo.name = 1.
    • Redbean might set the schema for column 'name' to be a TINYINT
  • Let's say I then set foo.name = 1234
    • Redbean might set the schema for 'name' to be an INT
  • Let's say I then set foo.name = 'abcdefg'.
    • Redbean might set the schema for 'name' to be VARCHAR(250).
It gets better though.  While it builds your schema, you're free to mess with your DB as much as you want behind the scenes (change schema, add indexes, etc) and redbean will still cooperate.  And once you're happy with the DB, you push to production and you want to make sure RedBean doesn't alter your schema, you add one line of code to the top of your PHP script to ensure that doesn't happen ('R::freeze()').  After that, if the DB is unhappy with what you're sending it, Redbean will just work as an ORM solution and pass back the error if the DB is unhappy with a given query.

Beyond that, check out the site.  The syntax is beautifully simple to understand and it's my ORM of choice at this point.


No comments: