I have been writing dynamic database-backed web applications since 2006, still whenever I fire up my IDE, I can’t help notice that the SQL in my code doesn’t feel natural, my IDE can’t parse it, because in essence, it’s a string that gets created on runtime. SQL itself can be pretty counter intuitive, it has poor support for complex data structures, one of it’s main weaknesses is that(to my knowledge) it can’t return nested structures. In terms of clarity, SQL doesn’t scale well, long SQL strings are really hard to understand.
In real life we have complex and nested data and we need to make our code as clear as possible. A common practice(MVC) is to put all the SQL into data access objects and use it’s API instead of raw SQL. I did just that I had most of my SQL in objects, what I found is that I kept repeating code and kept doing the same thing with every new data access object I made, but at least I always knew the purpose of the SQL queries, because they were encapsulated.
One day I kept hearing about NoSQL databases, they looked to offer something better but I ignored them because most hosting providers don’t support them. A while ago however I heard about object relational mappings(ORM), libraries which provide a native API on top of SQL. This sounded just like what I needed, something that could help eliminate the duplication I previously had with my data access objects.
I searched for an ORM written for PHP and I found Flourish ORM, after finding it I realized that this is what I needed all along. I can create a basic ActiveRecord in 3-4 lines of code, the only thing I need to specify is the database it maps to, the ORM layer reads the schema of the database and gives me dynamic methods that I can use instead of SQL.
//this is how we initialize class User extends fActiveRecord { } fORM::mapClassToTable('User', 'user'); //this is what we get $user = new User(); $user->setName('Test user'); $user->setPassword('123456'); $user->store();
That’s it, I get similar methods for the rest of the database operations, one of the main benefits is that I no longer have to worry about string concatenation. I can override these methods at any time using standard OOP techniques. Of course this does not mean that I will never write SQL again, but I will write and maintain a lot less that I was used to. Another big advantage is that there is a standard API for data handling, if someone takes over my code, I could simply point to the Flourish documentation.