I've been digging around for an ORM to use in a php/mysql application. However none quite grab my attention past "hello world" tests. So, I decided to do some research and try to code my own custom ORM. However I haven't been able to find resources that explain at code level how to handle db relationships. The concept of how an ORM works is clear but when trying to lay it out in code I don't know what the best approach is. Is it best to build several small queries or to build one complex query for every posible scenario? Any insight into the algorithm or architecture of an ORM is welcome!
Many ORMs these days are built around the Active Record pattern or variations thereof. In this scheme, you usually have automatically generated classes that correspond to each table in the database, each of those classes return an instance of themselves or of a subclass that correspond to each row in the table:
For example, if you have a Users table:
$user_list = Users.getAllUsers(); //SELECT * FROM Users
//foreach row, create a new User() instance
$user_list[0].name = "Peter";
//UPDATE Users SET name = 'Peter' WHERE user_id = <$user_list[0].id>
$user_list[0].commit();
About implementation, it's best to try to minimize the amount of queries sent to the server, but it's not always trivial nor desirable.
ORMs are not simple. Your ORM will be neither simple or efficient. If it's either of these then your application is simple enough to not need one in the first place, or you're punting when the problem gets hard and simply not using it.
Simple CRUD mapping an object to a table is easy. Start adding in relationships or collections, and everything goes to pot. Then there's queries, etc. The complexity increases in a non-linear, accelerating fashion.
Then the inevitable need for caching just to get it to perform adds even more fun and excitement to the project.
Pretty soon your project is consumed in tweaking, maintaining, and debugging the internal ORM, instead of advancing your project. If you took the time you invested in your ORM and simply wrote a DAO layer with SQL, your project would be farther along, simpler, and more efficient.
Frankly, adopting an ORM is hard enough to justify, depending on the project scale. Writing your own is even more likely not worth the investment.