Yii Framework Forum: Proposal: *All* components accept a configuration array / string as the first argument to their constructor - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Proposal: *All* components accept a configuration array / string as the first argument to their constructor

#1 User is offline   phpnode 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 141
  • Joined: 18-April 11

Posted 01 April 2012 - 02:27 PM

This would be quite a change, but I think it would be really useful. You almost always need to set certain values when creating a new object, e.g instead of:
$model = new User("myScenario");
$model->name = "My Name";
$model->address = "123 Fake Street";
$model->city = "Springfield";

It would be much nicer to be able to do:

$model = new User(array(
    "scenario" => "myScenario",
    "name" => "My Name",
    "address" => "123 Fake Street",
    "city" => "Springfield"
));


So in the new Yii\Component class

public function __construct($config = null)
{
    if ($config!==null)
        $this->configure($config);
    
}

public function configure($config)
{
    if(is_string($config))
        $config=require(Yii::getPathOfAlias($config).'.php');
    if(is_array($config))
    {
        foreach($config as $name=>$value)
            $this->$name=$value;
    }
}


If this is unacceptable for some reason, I think we should at the very least make configure() part of Yii\Component because it's such a common use case.
1

#2 User is offline   qiang 

  • Yii Project Lead
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,875
  • Joined: 04-October 08
  • Location:DC, USA

Posted 01 April 2012 - 02:38 PM

*
POPULAR

We actually have this in 2.0:
$comment = Comment::newInstance($config, $param1, $param2, ...).


newInstance is a static method defined in the Object base class in Yii. Its first parameter is used to configure the newly created object, while the rest of the parameters are passed to the constructor of the class. We don't want to force the signature of constructors because very likely people may override it.
6

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users