I am reading this documentation:
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html
This is an example model suggested in the guide,
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
What I don't understand is how is the saveAs() method being called in upload() function above:
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
According to whatever little php I know, methods are called either statically, like this:
UploadedFile::saveAs(..., ...);
Or non-statically like this:
$this->saveAs();
but in the latter case, must not the class from which the method is called, extend from the class which the method belongs to?
The saveAs() function belongs to the yii\web\Uploadedfile class. how can we call it the above mentioned way ( $this->imageFile->saveAs() )?
$this->imageFile, basically. once the upload has been processed interally, you simply have an object in there and can call its methods. - Marc B$this->saveAs(). there's$this->imageFile->saveAs(), because that uploadedfile object was placed into your$this->imageFilewhen the rules were processed. - Marc B$model->imageFile = UploadedFile::getInstance($model, 'imageFile')just before calling$model->upload()in the controller (here).$this->imageFilewill hold then an instance with asaveAs()method. - Salem Ouerdani