Implementation example of pjax in the slim framework

Source: Internet
Author: User

Pjax = pushState + ajax

Because this is a common component, I have written it into the Middleware of slim (if you do not know what the middleware is or how to write it, you can check it here)

The general principle is that after the slim framework is rendered and output, analyze the dom structure, extract the part required by pjax, and then return the content as the response to the browser's ajax request.

Preview: click the tab to view the effect.

The code is as follows: Copy code

$ App-> add (new \ Support \ PjaxMiddleware ());

<? Php
Namespace Support;

Use Slim \ Middleware;
Use Slim \ Http \ Request;
Use Slim \ Http \ Response;
Use Symfony \ Component \ DomCrawler \ Crawler;
Class PjaxMiddleware extends Middleware
{
Public function call ()
    {
$ Request = $ this-> app-> request ();
$ Response = $ this-> app-> response ();
$ This-> next-> call ();
If (! $ Request-> headers ('x-PJAX ') | $ response-> isRedirect ()){
Return;
        }
$ This-> filterResponse ($ response, $ request-> headers ('x-PJAX-CONTAINER ')-> setUriHeader ($ response, $ request );
    }
Private function filterResponse (Response $ response, $ container)
    {
$ Crawler = new Crawler ($ response-> getBody ());
$ Response-> setBody ($ this-> makeTitle ($ crawler). $ this-> fetchContents ($ crawler, $ container ));
Return $ this;
    }
Private function makeTitle (Crawler $ crawler)
    {
$ Title = $ crawler-> filter ('head> title')-> html ();
Return "<title >{$ title} </title> ";
    }
Private function fetchContents (Crawler $ crawler, $ container)
    {
$ Content = $ crawler-> filter ($ container );
If (! $ Content-> count ()){
$ This-> app-> stop ();
        }
Return $ content-> html ();
    }
Private function setUriHeader (Response $ response, Request $ request)
    {
$ Query = $ request-> get ();
Unset ($ query ['_ pjax']);
$ Response-> header ('x-PJAX-URL ', $ request-> getResourceUri ().'? '. Http_build_query ($ query ));
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.