?? How Laravel Query Builder Uses OOP

?? How Laravel Query Builder Uses OOP

Laravel’s Query Builder is an OOP-based abstraction layer over PDO (PHP Data Objects). It follows key OOP principles:

1?? Encapsulation ??? (Hides Complex DB Logic)

  • Laravel hides raw SQL queries and provides an easier way to interact with databases.
  • Example:

$users = DB::table('users')->where('id', 1)->get();        

  • Internally, Laravel encapsulates this into a prepared statement (SELECT * FROM users WHERE id = ?).



2?? Method Chaining ?? (Fluent Interface Pattern)

  • Laravel uses method chaining, allowing readable and flexible query construction.
  • Example:

$users = DB::table('users')
            ->where('status', 'active')
            ->orderBy('name', 'asc')
            ->limit(10)
            ->get();        

  • Each method (where(), orderBy(), limit()) modifies the query and returns the same object.


3?? Single Responsibility Principle (SRP) ???

  • Laravel separates concerns using different classes for:

Query building (Illuminate\Database\Query\Builder)

Database connections (Illuminate\Database\Connection)

Eloquent Models (Illuminate\Database\Eloquent\Model)        


4?? Factory & Static Methods ?? (Like Your DB::table())

  • Laravel’s DB::table('users') is a factory method that initializes an instance of Query\Builder.
  • Example:

use Illuminate\Support\Facades\DB;

$users = DB::table('users')->get();        

  • This creates a new instance of Query\Builder without manually instantiating it.


5?? Abstraction & Extensibility ?

  • Laravel hides the complexity of raw SQL queries, making it easy to extend.
  • Example:

Instead of writing:

 $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
$users = $stmt->fetchAll();        

Laravel lets you abstract that into:

   $users = DB::table('users')->where('id', 1)->get();        



?? Laravel Query Builder vs. Your OOP DB Class

Laravel follows OOP best practices like Encapsulation, Method Chaining, SRP, and Abstraction to make database queries secure, readable, and maintainable. ?


Vipurthanan Velnayagam

Full-Stack Developer | TALL Stack | TailwindCSS | Alpine | Laravel | Livewire | Government Pharmacist

1 个月

Very helpful

要查看或添加评论,请登录

Rusiru Nethmina的更多文章

社区洞察

其他会员也浏览了