PHP code example of xepozz / yii2-api-model-presenter

1. Go to this page and download the library: Download xepozz/yii2-api-model-presenter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xepozz / yii2-api-model-presenter example snippets


class User extends \yii\db\ActiveRecord
{
    public $firstName;
    public $lastName;

    public function fields()
    {
        return [
            'id' => 'id',
            'name' => function() {             
                return $this->firstName . ' ' . $this->lastName;
            },
        ];
    }
}

       /** @var $model \common\models\User */
       $model = $someService->getMyUser();
       
       return \api\modules\chat\models\User::findOne($model->id);
    

      /** @var $model \api\modules\chat\models\User */
      $model = $someService->getMyUser();
      
      return \common\models\User::findOne($model->id);
   

use Xepozz\Yii2ApiModelPresenter\ProxyPresenter;

/**
 * @property \common\models\User $record
 */
class UserPresenter extends ProxyPresenter
{
    protected function getFields(): array
    {
        return [
            'first_name',
            'last_name',
            'full_name' => function() {
                return sprintf('%s %s', $this->record->first_name, $this->record->last_name);        
            }
        ];
    }
}

use Xepozz\Yii2ApiModelPresenter\ProxyPresenter;

/**
 * @property \common\models\User $record
 */
class UserPresenter extends ProxyPresenter
{
    protected function getFields(): array
    {
        return [
            // ...
        ];
    }

    public function getExtraFields(): array
    {
        return [
            'messages' => 'chatMessages',
        ];
    }

    protected function setUpChildDefinitions(): array
    {
        return [
            'chatMessages' => ChatMessagePresenter::class,
        ];
    }
}

use Xepozz\Yii2ApiModelPresenter\ProxyPresenter;

/**
 * @property \common\models\User $record
 */
class UserPresenter extends ProxyPresenter
{
    protected function getFields(): array
    {
        return [
            'id',
            'status',
            'last_visited_at',
        ];
    }

    protected function getIgnoredFields(): array
    {
        return [
            /**
             * Скрываем на "prod" откружении поле email. Используется только для разработки
             */
            'id' => YII_ENV_PROD,
            'last_visited_at' => function() {
                /**
                 * Если статус online, тогда не показываем это поле.
                 */
                return (bool) $this->record->status;
            },
        ];
    }
}