I'm trying to do the Builder Pattern in PHP, and I'm trying to do it with fluent interface, but my problem is that it's not the same as it would be in Java.
I put a simple example to illustrate the doubt of how the same pattern would be done in PHP:
We have the User class which represents a model of our application.
class Usuario{
private $username;
private $password;
private $email;
public function __construct($username, $password, $email) {
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
/*Getters y Setter de las variables*/
We have a Builder class ( UserBuilder ) to create objects of the User class which has the methods to build the object:
class UsuarioBuilder {
private $username = '';
private $password = '';
private $email = '';
public function withUserName($username) {
$this->username = $username;
return $this;
}
public function withPassword($password) {
$this->password= $password;
return $this;
}
public function withEmail($email) {
$this->email = $email;
return $this;
}
public function build() {
return new Usuario($this->username, $this->password, $this->email);
}
}
That would be the class I use to have the Builder and create the User objects from that class. But this is where it gives me an error and I don't know how to do it. Trying to create a User object through the UserBuilder class gives me an error:
$rodriUser = new UsuarioBuilder()
->withUserName('Rodri')
->withPassword('123456a')
->withEmail('[email protected]')
->build();
It doesn't let me (as it would be in Java) from the constructor of the UserBuilder class to call the rest of the methods and I get a syntax error on the line when I call the first method "->withUserName()". I can't call methods from the constructor like in Java you can. What would be the correct way to implement this pattern in PHP?
Enclose the initialization operation in parentheses so that it returns the instance so you can access its members:
The error is probably due to the syntax not being recognized by the php interpreter.
Update:
Good to note that syntax only works since php 5.4.0 and the name is Class Member Access on Instance