【问题标题】:How to use model attribute value in behavior config Yii如何在行为配置 Yii 中使用模型属性值
【发布时间】:2014-05-22 11:45:27
【问题描述】:

我想创建ImageBehavior 用于上传和保存图像。我的行为有两个字段:imagePathimageField。在我的模型中,我写道:

public function behaviors(){
    return array(
        'imageBehavior' => array(
            'class' => 'ImageBehavior',
            'imagePath' => 'images/avatar-pics/'.$this->user->username,
            'imageField' => 'avatar',
        ),
    );
}

但这不起作用 - 我收到了路径 -

images/avatar-pics//image.png

什么解决方案?在行为字段imageFolder 中创建并添加到配置'imageFolder' => 'user->username'?谢谢。

【问题讨论】:

    标签: php yii model behavior


    【解决方案1】:

    作为建议:

    改变你使用行为的方式,并为你的模型添加一些代码。看看下面的例子:

    例如,您的behavior:

    class ImageBehavior extends CBehavior {
        public $imagePath;
        public $imageField;
        public function getImagePath() {
            return $this->imagePath;
        }
    }
    

    你的model

    class TestModel extends CFormModel {
    
        private $imagePath = '/home/x/y';
    
        public function setImagePath($imagePath) {
    
            $this->imagePath = $imagePath;
            $this->attachBehaviors(array(
                array(
                    'class' => 'ImageBehavior',
                    'imagePath' => $this->imagePath
                )
            ));
        }
    
        public function init() {
            $this->setImagePath($this->imagePath);
            parent::init();
        }
    
    }
    

    现在,看看测试和结果:

    $model=new TestModel();
    CVarDumper::dump($model->getImagePath()); //output: /home/x/y
    
    $model->setImagePath('/home/x/path2');
    CVarDumper::dump($model->getImagePath()); //output: /home/x/path2
    
    $model->setImagePath('/home/x/path3');
    CVarDumper::dump($model->getImagePath()); //output: /home/x/path3
    

    这样,如果你没有设置任何imagePath,它使用模型的默认值。在前面,每次你更改imagePath 你的路径都会改变你的行为。

    注意:这只是一个建议。通过这种方式,您可以自定义您的 setImagePath 方法以从您想要的任何地方(另一个模型、会话等...)获取值。

    【讨论】:

      【解决方案2】:

      很抱歉回答了自己的问题,但差不多两年后对这个问题建立了正确的看法:

      1) 不要使用线

      'images/avatar-pics/'.$this->user->username

      在您的行为中 - 它会发出“试图获取非对象的属性”的通知 - 好的应用程序不会发出通知和警告。

      2) 你只需要使用

      'images/avatar-pics/' . CHtml::value($this, 'user.username') 
      

      相反。如果 $this->user 为 null,则 value 方法返回 null,因此请确保您的模型有相关用户。

      【讨论】:

        【解决方案3】:
        //inside the behavior:
        $this->owner->user->username;
        

        $this->owner - 这是你的模型。行为是在填充属性之前初始化的,初始化后才能获取属性值。

        【讨论】:

        • 错误的解决方案。对于一个模型来说,这种方式是可行的,但对于另一个模型呢?在第二个模型中,我需要设置 'imagePath' => 'images/help/'.$this->id - 我失去了灵活性。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多