search
HomePHP FrameworkYIIYii2 API interface output unified Json and jsonp format method

Yii2 API interface output unified Json and jsonp format method

If you are making an API, how can you enable others to have a unified and standard json or jsonp format when they call your interface? However, the format and content of the json response are everyone’s agreement. There are differences, so we must do certain processing before the data is sent out.

1. First we need to initialize to call beforeSend, because we need to do some processing on beforesend. The following is the init initialization processing code:

/**
 * (non-PHPdoc)
 * @see \yii\base\Object::init()
 */
public function init()
{       
    parent::init();	//绑定beforeSend事件,更改数据输出格式
    Yii::$app->getResponse()->on(Response::EVENT_BEFORE_SEND, [$this, 'beforeSend']);
}

2. Then we need to process beforesend. The processing points have the following key points:

1>Change the data output format

2>Json data is output by default

3>If the client passes the $_GET['callback'] parameter when requesting, the output will be in Jsonp format

4>When the request is correct, the data will be {"success":true,"data":{.. .}}

5>The data when requesting an error is {"success":false,"data":{"name":"Not Found","message":"Page not found.","code ":0,"status":404}}

6>The specific code is as follows:

/**
     * 更改数据输出格式
     * 默认情况下输出Json数据
     * 如果客户端请求时有传递$_GET['callback']参数,输入Jsonp格式
     * 请求正确时数据为  {"success":true,"data":{...}}
     * 请求错误时数据为  {"success":false,"data":{"name":"Not Found","message":"页面未找到。","code":0,"status":404}}
     * @param \yii\base\Event $event
     */
    public function beforeSend($event)
    {        /* @var $response \yii\web\Response */
        $response = $event->sender;
        $isSuccessful = $response->isSuccessful;        if ($response->statusCode>=400) {            //异常处理
            if (true && $exception = Yii::$app->getErrorHandler()->exception) {
                $response->data = $this->convertExceptionToArray($exception);
            }            //Model出错了
            if ($response->statusCode==422) {
                $messages=[];                foreach ($response->data as $v) {
                    $messages[] = $v['message'];
                }                //请求错误时数据为  {"success":false,"data":{"name":"Not Found","message":"页面未找到。","code":0,"status":404}}
                $response->data = [                    'name'=> 'valide error',                    'message'=> implode("  ", $messages),                    'info'=>$response->data
                ];
            }
            $response->statusCode = 200;
        }        elseif ($response->statusCode>=300) {
            $response->statusCode = 200;
            $response->data = $this->convertExceptionToArray(new ForbiddenHttpException(Yii::t('yii', 'Login Required')));
        }        //请求正确时数据为  {"success":true,"data":{...}}
        $response->data = [            'success' => $isSuccessful,            'data' => $response->data,
        ];
        $response->format = Response::FORMAT_JSON;
        \Yii::$app->getResponse()->getHeaders()->set('Access-Control-Allow-Origin', '*');
        \Yii::$app->getResponse()->getHeaders()->set('Access-Control-Allow-Credentials', 'true');       //jsonp 格式输出
        if (isset($_GET['callback'])) {
            $response->format = Response::FORMAT_JSONP;
            $response->data = [                'callback' => $_GET['callback'],                'data'=>$response->data,
            ];
        }
    }

3. Some exceptions may occur in response to requests, and we also need to handle exceptions. Some standardized processing converts exceptions into array output. The specific code is as follows:

/**
     * 将异常转换为array输出
     * @see \yii\web\ErrorHandle
     * @param \Exception $exception
     * @return multitype:string NULL Ambigous <string, \yii\base\string> \yii\web\integer \yii\db\array multitype:string NULL Ambigous <string, \yii\base\string> \yii\web\integer \yii\db\array
     */
    protected function convertExceptionToArray($exception)
    {        if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) {
            $exception = new HttpException(500, Yii::t(&#39;yii&#39;, &#39;An internal server error occurred.&#39;));
        }
        $array = [            &#39;name&#39; => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : &#39;Exception&#39;,            &#39;message&#39; => $exception->getMessage(),            &#39;code&#39; => $exception->getCode(),
        ];        if ($exception instanceof HttpException) {
            $array[&#39;status&#39;] = $exception->statusCode;
        }        if (YII_DEBUG) {
            $array[&#39;type&#39;] = get_class($exception);            if (!$exception instanceof UserException) {
                $array[&#39;file&#39;] = $exception->getFile();
                $array[&#39;line&#39;] = $exception->getLine();
                $array[&#39;stack-trace&#39;] = explode("\n", $exception->getTraceAsString());                if ($exception instanceof \yii\db\Exception) {
                    $array[&#39;error-info&#39;] = $exception->errorInfo;
                }
            }
        }        if (($prev = $exception->getPrevious()) !== null) {
            $array[&#39;previous&#39;] = $this->convertExceptionToArray($prev);
        }        return $array;
    }

Okay, so we have the same standard api interface return data format, and the person who calls the interface also Don’t worry about inconsistent formats

Recommended: "Yii2.0 Framework Development Practical Video Tutorial"

The above is the detailed content of Yii2 API interface output unified Json and jsonp format method. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:YII中文网. If there is any infringement, please contact admin@php.cn delete
Yii: The Rapid Development FrameworkYii: The Rapid Development FrameworkApr 14, 2025 am 12:09 AM

Yii is a high-performance framework based on PHP, suitable for rapid development of web applications. 1) It adopts MVC architecture and component design to simplify the development process. 2) Yii provides rich functions, such as ActiveRecord, RESTfulAPI, etc., which supports high concurrency and expansion. 3) Using Gii tools can quickly generate CRUD code and improve development efficiency. 4) During debugging, you can check configuration files, use debugging tools and view logs. 5) Performance optimization suggestions include using cache, optimizing database queries and maintaining code readability.

The Current State of Yii: A Look at Its PopularityThe Current State of Yii: A Look at Its PopularityApr 13, 2025 am 12:19 AM

YiiremainspopularbutislessfavoredthanLaravel,withabout14kGitHubstars.ItexcelsinperformanceandActiveRecord,buthasasteeperlearningcurveandasmallerecosystem.It'sidealfordevelopersprioritizingefficiencyoveravastecosystem.

Yii: Key Features and Advantages ExplainedYii: Key Features and Advantages ExplainedApr 12, 2025 am 12:15 AM

Yii is a high-performance PHP framework that is unique in its componentized architecture, powerful ORM and excellent security. 1. The component-based architecture allows developers to flexibly assemble functions. 2. Powerful ORM simplifies data operation. 3. Built-in multiple security functions to ensure application security.

Yii's Architecture: MVC and MoreYii's Architecture: MVC and MoreApr 11, 2025 pm 02:41 PM

Yii framework adopts an MVC architecture and enhances its flexibility and scalability through components, modules, etc. 1) The MVC mode divides the application logic into model, view and controller. 2) Yii's MVC implementation uses action refinement request processing. 3) Yii supports modular development and improves code organization and management. 4) Use cache and database query optimization to improve performance.

Yii 2.0 Deep Dive: Performance Tuning & OptimizationYii 2.0 Deep Dive: Performance Tuning & OptimizationApr 10, 2025 am 09:43 AM

Strategies to improve Yii2.0 application performance include: 1. Database query optimization, using QueryBuilder and ActiveRecord to select specific fields and limit result sets; 2. Caching strategy, rational use of data, query and page cache; 3. Code-level optimization, reducing object creation and using efficient algorithms. Through these methods, the performance of Yii2.0 applications can be significantly improved.

Yii RESTful API Development: Best Practices & AuthenticationYii RESTful API Development: Best Practices & AuthenticationApr 09, 2025 am 12:13 AM

Developing a RESTful API in the Yii framework can be achieved through the following steps: Defining a controller: Use yii\rest\ActiveController to define a resource controller, such as UserController. Configure authentication: Ensure the security of the API by adding HTTPBearer authentication mechanism. Implement paging and sorting: Use yii\data\ActiveDataProvider to handle complex business logic. Error handling: Configure yii\web\ErrorHandler to customize error responses, such as handling when authentication fails. Performance optimization: Use Yii's caching mechanism to optimize frequently accessed resources and improve API performance.

Advanced Yii Framework: Mastering Components & ExtensionsAdvanced Yii Framework: Mastering Components & ExtensionsApr 08, 2025 am 12:17 AM

In the Yii framework, components are reusable objects, and extensions are plugins added through Composer. 1. Components are instantiated through configuration files or code, and use dependency injection containers to improve flexibility and testability. 2. Expand the management through Composer to quickly enhance application functions. Using these tools can improve development efficiency and application performance.

Yii Theming and Templating: Creating Beautiful & Responsive InterfacesYii Theming and Templating: Creating Beautiful & Responsive InterfacesApr 07, 2025 am 12:03 AM

Theming and Tempting of the Yii framework achieve website style and content generation through theme directories and views and layout files: 1. Theming manages website style and layout by setting theme directories, 2. Tempting generates HTML content through views and layout files, 3. Embed complex UI components using the Widget system, 4. Optimize performance and follow best practices to improve user experience and development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools