F
F
Flaker2014-06-20 18:10:13
Yii
Flaker, 2014-06-20 18:10:13

(Yii2) What is the best way to organize the interaction of the avatar display widget with the avatar manager?

Continuing the question: (Yii2) What is the best way to deal with user avatars?
I'm trying to decide how to make an optimal structure for working with an avatar and displaying it using a widget.

  • Avatar Widget should display a block with the specified user's avatar.
  • Options and methods for working with avatars are stored in the Avatar Manager .
  • An unlimited number of avatars can be displayed on the page, and Avatar::Widget() in the loop will not be optimal in terms of time, since the object is recreated each time.
  • Avatar Widget takes the URL of the image from the Avatar Manager .

I made this option:
There is an AvatarManager whose constructor accepts User Model or just user_id (in config )
Code Avatar Manager

public $user_id;
public function __construct(User $UserModel = null, $config = [])
{
    parent::__construct($config);
    $this->_UserModel = $UserModel;
}
public function getAvatarUrl()
{
    // Возвращает URL картинки
}

If there is no user_id in $config , then it is filled from the model. In the Avatar Widget , $user_id is also taken from $config or the current user, and an Avatar Manager object is created . The content method returns the generated HTML code. And the run method displays it.


Code Avatar Widget

public $user_id;

private $_AvatarManager;

public function init()
{
    parent::init();

    $this->user_id = isset($this->user_id) ? $this->user_id : Yii::$app->user->identity->getId();

    $this->_AvatarManager = new AvatarManager(null, ['user_id' => $this->user_id]);
}
public function run($user_id = null)
{
    echo $this->content($user_id);
}
public function content($user_id = null)
{
    if (isset($user_id))
        $this->_AvatarManager->user_id = $user_id;
    $img_url = $this->_AvatarManager->getAvatarUrl();
    $content = // Генерация контента
    return $content;
}

Now, to display a large number of avatars in the View, I create an AvatarManager object and call the run () method where required:
$avatar = new AvatarManager();
$avatar->run(1)
$avatar->run(2)
$avatar->run(3)
...
$avatar->run(10000)

Have I taken the right approach?
How to do it better / right?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question