我正在尝试从header.php调用下面的函数。但我得到一个错误。当我从我的视图文件(profile.php)中调用它时,它可以正常工作。
在我的 /model/User.php
中public function getAvatar() {
$dir = 'uploads/user';
$img = $this->avatar_link;
$full_img_dir = './'.$dir.'/'.$this->id.'/'.$img;
return (!empty($this->avatar_link) && file_exists($full_img_dir))
? Yii::app()->request->baseUrl.'/'.$dir.'/'.$this->id.'/'.$img
: Yii::app()->request->baseUrl.'/images/blank_profile.gif';
}
这是我得到的错误
Property "UserController.avatar_link" is not defined.
我正在调用这个函数
<img class="img-rounded user-avatar" src="<?php echo User::getAvatar(); ?>" title="<?php echo Yii::app()->user->username; ?>" />
这是我的 models / User.php
<?php
/**
* This is the model class for table "user".
*
* The followings are the available columns in table 'users':
* @property string $id
* @property string $username
* @property string $email
* @property string $first_name
* @property string $last_name
* @property string $address
* @property string $city
* @property string $state
* @property string $postcode
* @property string $phone
* @property string $password
* @property string $activate
* @property string $last_login
* @property string $password_reset
* @property integer $admin
* @property integer $email_verified
* @property integer $login_disabled
*/
class User extends CActiveRecord {
/**
* Used for password change and registration
*/
public $pass1;
public $pass2;
public $old_password;
public $verify;
public $state_name;
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return User the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName() {
return 'user';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('email, first_name, last_name', 'required', 'on' => 'create, register'),
array('email', 'unique'),
array('email', 'exist', 'on' => 'forgotPassword'),
array('old_password', 'site.common.components.validate.ECurrentPassword', 'on' => 'changePassword'),
array((app()->user->isAdmin() ? 'pass1, pass2' : 'old_password, pass1, pass2'), 'required', 'on' => 'changePassword'),
array('pass1, pass2', 'required', 'on' => 'resetPass'),
array('pass2', 'compare', 'compareAttribute' => 'pass1', 'on' => 'resetPass, changePassword'),
array('pass1, pass2', 'site.common.components.validate.EPasswordStrength', 'on' => 'resetPass, changePassword'),
array('password, pass2', 'required', 'on' => 'register'),
array('pass2', 'compare', 'compareAttribute' => 'password', 'on' => 'register'),
//array('verify', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'register, forgotPassword'),
array(
'validation',
'site.common.extensions.recaptcha.EReCaptchaValidator',
'privateKey'=> Yii::app()->params['recaptcha']['privateKey'],
'on' => 'register, forgotPassword'
),
array('admin, email_verified, login_disabled', 'numerical', 'integerOnly' => true),
array('email, password', 'length', 'max' => 63),
array('address', 'length', 'max' => 150), //originally 511
array('postcode, city, state, state_name', 'length', 'max' => 50),
array('phone_area, phone', 'length', 'max' => 10), //originally 12
array('gender, birthday', 'length', 'max' => 20),
array('first_name, last_name', 'length', 'max' => 45),
array('password_reset', 'numerical', 'on' => 'passwordReset', 'integerOnly' => true),
array('password, pass2', 'site.common.components.validate.EPasswordStrength', 'on' => 'register'),
array('email', 'email', 'on' => 'update, create, register'),
array('first_name, last_name', 'site.common.components.validate.ENameValidator'),
array('email', 'unique', 'on' => 'create, register'),
array('email, phone', 'default', 'setOnEmpty' => true), // make empty values stored as NULL
array('last_login', 'safe'),
array('username', 'unique', 'on' => 'consumer-reviews'),
array('username', 'site.common.components.validate.EUsernameValidator', 'on' => 'consumer-reviews'),
//array('username', 'unique','className'=>'User','attributeName'=>'username','message'=>"Username already exists"),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, email, first_name, last_name, phone, admin, email_verified, login_disabled', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'username' => 'Username',
'email' => 'Email',
'firstname' => 'First Name',
'lastname' => 'Last Name',
'address' => 'Address',
'city' => 'City',
'state' => 'State',
'state_name' => 'State',
'postcode' => 'Poscode',
'phone_area' => 'Phone Area',
'phone' => 'Phone',
'password' => 'Password',
'activate' => 'Activate',
'last_login' => 'Last Login',
'password_reset' => 'Password Reset',
'admin' => 'Admin',
'email_verified' => 'Email Verified',
'login_disabled' => 'Login Disabled',
'pass1' => 'New Password',
'pass2' => 'Confirm Password',
'old_password' => 'Current Password',
'validation'=> 'Are You Human?!',
// 'verify' => 'Validate',
);
}
/**
* Automatic add the current time to create_at field once registered
*/
public function behaviors(){
//The createAttribute and updateAttribute options actually default to 'create_time' and 'update_time' respectively
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'create_at',
'updateAttribute' => 'last_login',
)
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('email', $this->email, true);
return $criteria;
}
public function isAdmin() {
return $this->admin;
}
public static function findByEmail($email) {
return self::model()->findByAttributes(array('email' => $email));
}
/**
* Create new user object, do not save it to database yet
* all permission should be valid now
* @param type $input
*/
public static function create($input) {
if (isset($input['email'])) {
$model = self::findByEmail($input['email']);
} else {
$model = new User;
}
$password = isset($input['password']) ? $input['password'] : '';
if (null == $model) {
// used by admin for creating a user (be sure to send the random password to the user...)
$model = new User;
$model->attributes = $input;
if (strlen($model->password) == 0) {
// create new one if nothing is provided (only applies to admins creating new users)
$password = Shared::generateMnemonicPassword(8);
} else {
$password = $model->password;
}
$model->password = crypt($password, Randomness::blowfishSalt());
$model->pass1 = $password;
$model->email = strtolower($model->email);
}
return $model;
}
public function getFullName() {
return $this->first_name . ' ' . $this->last_name;
}
public function getAvatar() {
$user = User::model()->findByPk(Yii::app()->user->id);
$id = $user->id;
$dir = 'uploads/user';
$img = $user->avatar_link;
$full_img_dir = './'.$dir.'/'.$id.'/'.$img;
return (!empty($img) && file_exists($full_img_dir))
? Yii::app()->request->baseUrl.'/'.$dir.'/'.$id.'/'.$img
: Yii::app()->request->baseUrl.'/images/blank_profile.gif';
}
/**
* Generate an encrypted hash for the user
* @param type $string
* @param type $hash
* @return type
*/
public static function encrypt($string = "", $hash = "md5") {
if ($hash == "md5")
return md5($string);
if ($hash == "sha1")
return sha1($string);
else
return crypt($hash, $string);
}
/**
* Function called before update.
* @param type $password
*/
public function setPassword($password) {
if (strlen($password) > 0) {
// change password
$this->password = crypt($password, Randomness::blowfishSalt());
} else {
// keep the original one
$this->restoreAttribute('password');
}
}
}
我在做错了什么?感谢
答案 0 :(得分:1)
您将非静态方法称为静态,使用$ this而不使用任何对象,这是您的错误。 如何实现你想要的? 首先你必须有User对象,使用$ this和非静态方法。
$user = User::model()->findByPk(Yii::app()->user->id);
接下来(如果你有所有领域)你可以称之为:
<img class="img-rounded user-avatar" src="<?php echo $user->getAvatar(); ?>" title="<?php echo Yii::app()->user->username; ?>" />
在这种情况下,你的$ this in function将是用户模型,否则它的控制器(在所有视图中$ this这是控制器)。你也可以将它用作$user->avatar
,因为它是yii getter。
修改强>
如何使用Yii::app()->user->avatar_link
1st。制作您的WebUser类并将其添加到components-&gt;用户部分的配置中(我假设它已经存在)
'user' => array(
'class' => 'RWebUser',
第二。为avatar_link制作getter和setter:
public function setAvatar_link($avatar_link)
{
$this->setState('User_avatar_link', $avatar_link);
}
public function getAvatar_link()
{
$this->getState('User_avatar_link');
}
第3次。将逻辑添加到afterlogin()
以获取您的头像链接:
public function afterLogin($fromCookie)
{
parent::afterLogin($fromCookie);
$user = User::model()->findByPk(Yii::app()->user->id);
$id = $user->id;
$dir = 'uploads/user';
$img = $user->avatar_link;
$full_img_dir = './'.$dir.'/'.$id.'/'.$img;
$avatar_link = (!empty($img) && file_exists($full_img_dir))
? Yii::app()->request->baseUrl.'/'.$dir.'/'.$id.'/'.$img
: Yii::app()->request->baseUrl.'/images/blank_profile.gif';
$this->setAvatar_link($avatar_link);
}
现在您可以将它与Yii::app()->user->avatar_link
一起使用,它将存储在会话中,并在用户登录时再查询一次。
答案 1 :(得分:1)
将其称为User :: model() - &gt; getAvatar()而不是User :: getAvatar();