A
A
akula222015-12-14 23:52:33
Yii
akula22, 2015-12-14 23:52:33

Displaying an avatar in one method, how to do it in OOP?

I'm just learning OOP and Yii2.
I want to display the user's avatar in a simple way, but I need to check if there is an avatar in the database, if there is a file in the folder.
And I just need to write in one place <?= \modules\user\Module::getAvatar($model->user->profile->avatar)?> and the method returned html::a(img, etc.
in the user module I define properties public static $ avatarPath
= '@app/public_html/upload/images/avatar';
public static $avatarUrl = '/upload/images/avatar';
public static $noAvatar = '/upload/images/avatar/noavatar. png';
but I can't figure out how to draw the method itself

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander N++, 2015-12-15
@sanchezzzhak

it’s not easier to make a user method in the model
And in the view to display something like this

<?php if(!Yii::$app->user->isGuest):?>
        <?=yii\helpers\Html::img( Yii::$app->user->getIdentity(true)->getAvatar() )?>
    <?php endif;?>

ps Yii::$app->user->getIdentity(true) Must be called once with true parameter, all other times it is better to use with false parameter.
You can access the module from the view like this
$this->context itself is the current controller/action/widget
Option 3 Create a static method wherever you want.

E
Evgeny Bukharev, 2015-12-15
@evgenybuckharev

Install the costa-rico/yii2-images extension from the github, there will be a table in the database out of the box, and a method that will display the avatar, or the url to the avatar, there is also a dynamic slicing functionality

I
Igorrebega, 2016-01-14
@Igorrebega

In the Profile model, you make a method

function getAvatar(){
 if($this->photo){
  return $this->AvatarUrl. $this->photo;
 }
 return $this->noAvatar;
}

Far in view
<?= Html::img($model->user->profile->avatar);?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question