Getposted Function

Hi,

Today we have the following code:


$model=new ContactForm;

if(isset($_POST['ContactForm']))

{

    $model->attributes=$_POST['ContactForm'];

    (...)

}

I suggest add the getPosted() function to CModel, so you can turn the previous code into this:


$model=new ContactForm;

if($model->posted)

{

    $model->attributes=$model->posted;

    (...)

}

Advantages:

  • More code reusing

  • We can change the class name and the controllers still work without any other change

I’ve been using this in my projects, and it is a tiny feature that actually helps. Here it is my implementation:


public function getPosted() {

    $name = get_called_class();

    if (isset($_POST[$name])) {

        return $_POST[$name];

    } else {

        return false;

    }

}

Or …




$model=new MyModel;

if($this->isPostRequest())

{

    $model->bindData();

    (...)

}



I don’t think models should contain request related stuff.

This would fit better:




public function getRequest{

    return Yii::app()->getRequest();

}

public function actionIndex()

    $model=new MyModel;

    if($this->request->isPostRequest) {

        $model->attributes = $this->request->getPost($model); //change getPost() so it accepts CModel as a parameter as well

        (...)

    }

}

;)

Seems fine to me too :)

That’s how it’s now ;)

I prefer using CForm Builder and doing:




if ( ( $form->submitted('submit') )

{


}



this automatically sets the post attributes to the model too.