Skip to content
Advertisement

Which type of PHP Object pattern use case it is?

Consider the following code:

UM()->Activity_API()->api()->get_author( $id )

I am confused with what is UM() here. Is it a class? If yes then why it is referred with round brackets, and how Activity_API() method is further refereed to api() method and then get_author() method?

Advertisement

Answer

In your specific example, UM is not a class, but a function that returns an object that has a public Activity_API() method.

E.g.

class Foo {
    public function Activity_API() 
    {
        echo "hello";
    }
}

function UM(): Foo {
    return new Foo();
}

UM()->Activity_API();

This one specifically is documented here. The function UM() returns an instance of UM, a class of the same name.

This kind of approach is simply used to have a more concise and explicit builder. You could do exactly the same by doing:

(new UM())->Activity_API()->api()->get_author( $id )

Each of the methods in the chain return another object. In this case another instance of UM.

Since each method in the chain returns another object, you can call any public method or access any public property of the returned object without creating any intermediate variable.

This is called a “Fluent Interface“:

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language. The term was coined in 2005 by Eric Evans and Martin Fowler.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement