DB::table('users')->select('name','surname')->where('id', $userId)->get(); 

What is the structure of the class in this code?

It turns out the static method table class DB is called, and select , where is that class variables? What about the get() function in a function?

  • table returns an object, then select on this object returns an object, then where , at the end, the get method is called on the object that returned where . - Suvitruf
  • If you are given an exhaustive answer, mark the answer with a decision so that it does not hang in the open. - Alex

1 answer 1

Sequential execution of DB class methods:

  1. DB::table('users') - the table method is executed, will return an instance of the DB class for building a database query associated with the users table;
  2. ->select('name','surname') - the select method is executed with variable length arguments;
  3. ->where('id', $userId) - the where method is executed with variable length arguments;
  4. ->get() - the get method is executed that forms the query and receives the results.

In paragraphs 1, 2, 3, an instance of the DB class ( object() ) is returned to build a query to the database. Most likely, when executing these methods, the DB class variables are assigned corresponding values ​​for the query, which are then used to construct the query during execution ->get() .


UPD - useful links

As rightly pointed out by @Deonis, this implementation is called a " fluent interface (fluent interface) ".

Useful links with examples and descriptions:

  1. Wikipedia - Fluent interface
  2. Habrahabr - Flowing Interface Programming Template in PHP
  3. Habrahabr - “Advanced Flow Interface”
  4. Habrahabr - “Design Patterns with a Human Face”
  • one
    It can be added that such an implementation is called a “fluent interface” (fluid interface) - Deonis
  • one
    I would add, saying that there is a pattern builder still mixed. And so the structure is as follows: In the DB class there are all these methods plus one get () method, which slips everything in front of it into a class that is focused on a sample from the habrahabr.ru/company/mailru/blog/325492/… database - dpi