Boris Mikhaylov
Boris Mikhaylov

Reputation: 329

Which approach is better when passing settings to an object?

I want to set initial values of fields in an object, using $config. Which approach is better in terms of cleaner and more maintainable code? Also, I would like to add that object will be initialized in a factory and not directly by client.

1. I pass $config to the object

<?php
class UserGreeting {
  private $config;
  public function __construct($config){
      $this->config=$config;
  }

  public function greetings(){
    echo 'Hello, '.$this->config->get('username');
  }
}
?>

Pros:

Cons:

2. I set fields manually outside the object

<?php
class UserGreetingFactory{
   public function __construct($config){
     $this->config=$config;
   }
   public function getUserGreeting(){
     $userGreeting=new UserGreeting();
     $userGreeting->setUserName='John Doe';
     return $userGreeing;
   }
} 

class UserGreeting {
   private userName;
   public function setUserName($userName){
     $this->userName=$userName;
   }
   public function greetings(){
     echo "Hello, {$this->userName}";
   }
  }
?>

Pros:

Cons:

Upvotes: 1

Views: 296

Answers (4)

Philippe Gerber
Philippe Gerber

Reputation: 17836

First solution with ctor injection. But instead of a special config i would just pass the actual objects. In your case an User object.

<?php
class UserGreeting
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function greet()
    {
        printf('Hello, %s!',  $this->user->getName());
    }
}

Upvotes: 1

Cups
Cups

Reputation: 6896

You could use a static class with static methods. In effect they are like CONSTS, but you can enforce all kinds of rules within the static config class - that they conform to an interface for example.

Config::getUserName();

That way if you are going to be faced with a family of config objects, you can be assured they all have at least an entry for each expected value - otherwise a warning is chucked.

Might depend on your situation of course, and I expect there are many situations where you would not want to do this - but I will offer it up all the same.

Upvotes: 0

vsushkov
vsushkov

Reputation: 2435

The first way is better because of dependency injection. This code will be easier to test and to maintain. The third way is to use Visitor pattern to inject dependencies.

Upvotes: 0

Tim S.
Tim S.

Reputation: 13843

Considering your idea's, I'd stick to a single variable. If you want to pass the variables per-method you'll have a lot of excessive code.

From an OOP point of view, you shouldn't put it in a single variable. An object has properties. An username is in fact a property so you should use it as property. That means that in PHP classes you'd need to make it a public variable and set the variables when you create the object.

Upvotes: 0

Related Questions