PHP code example of the-real-start / yii2-jsend-response

1. Go to this page and download the library: Download the-real-start/yii2-jsend-response 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/ */

    

the-real-start / yii2-jsend-response example snippets



// your template class
// templates needs for formating data section in response (remove some data for example)
use TRS\RestResponse\templates\BaseTemplate
class ProductSmallTemplate extends BaseTemplate
{
    protected function prepareResult()
        {
            $this->result = [
                'id'          => $this->model->id,
                'title'       => $this->model->title,
                'description' => $this->model->description,
                // exclude other fields (prices, discounts etc.)
            ];
        }
}

// model
class Product extends BaseProduct
{
    // you can use any other method name
    public function getAsArray($template = 'small')
        {
            if ($template == 'small') {
                $template = new ProductSmallTemplate($this);
            } else {
                throw new \InvalidArgumentException('Invalid template "' . $template . '"');
            }
            return [ 'Product' => $template->getAsArray() ];
        }
}

// controller
use TRS\RestResponse\jsend\Response
class ProductsController extends BaseController
{
    public function actionShow($id)
    {
        $product = Product::find()->localized()->andWhere(['id' => $id])->one();
        Response::success($product->getAsArray('small'))->send();
    }
}