Search code examples
phpdomain-driven-designdata-access-layerlaravel

SQL statements vs MVC data access layer in PHP


Modern MVC frameworks have their own implementation of data access layers that do not require SQL statements to be written. In terms of performance and scalability, are there any drawbacks, for instance, when using

$user = User::where('email', '=', $email)->first(); 

instead of using prepared statements in raw SQL like

$user = DB::connection()->pdo->prepare("SELECT * from users where `email` = ? "  ) ;

Since MVC frameworks like Laravel and Cakephp also allow the latter approach, I am not sure which of the two method is better in terms of performance and scalability.


Solution

  • Rant:
    What you call "modern MVC frameworks" (with few exceptions) are nowhere close implementing MVC. And those "layers that do not require SQL statements" are actually extremely harmful in large scale projects(where MVC should be actually used).

    My advice would be to avoid use of any built-in ORM or query-builder. The ORMs that so-called "mvc frameworks" are bundled with are usually implementations of active record, which has extremely limited use-case. Basically, AR based implementations for domain entities are pragmatic only if you are using just the basic CRUD operations (no JOINs or other above-beginner level sql queries) and only simple attribute validation (no cross-checked fields or interactions with other entities). Technically you can use active record instances in more complicated cased, but then you ill start to incur technical debt.

    The best option would be to separate the domain logic from storage logic and implement domain objects and data mappers for each of the aspect of model layer respectively.