Using PHP for its intended purpose


    upd: Caution, the text contains satire and codebase

    PHP programming language dates back to 1995 and is a product of the era of the emergence of modern web standards, such as http (version 1.0 - 1996), html (version 2.0 - 1995), javascript (1995) url (1990 - 1994). Initially, the abbreviation php was decoding Personal Home Page Tools, then transformed into Hypertext Preprocessor or "hypertext preprocessor". The following paragraphs will be devoted to using PHP as a preprocessor.

    PHP interpreter allows you to insert special tags into any text, with which you can substitute dynamic content into the page, which is very convenient to use inside html documents. The result is immediately sent to a standard output device, known as stdout (see here for details ). It is possible to buffer the output to demand via the ob_start function , but this is not needed for our first html page. The most recent html standard at number 5 introduced several new tags to simplify markup, increase the readability and semantics of the web (whatever that means). Therefore, we immediately take advantage of the full power of HTML5 and write a page template with inserts on the preprocessor in question.


    Save this page to the index.html file. The blog’s functionality in its first version will provide for storing publications in the form of html pages inside a predetermined directory (for example pages /) and a menu allowing you to go directly to the desired publication.

    An example of a publication that will be displayed in the blog feed.


    Add the pages / directory to the project root and save our article under an arbitrary name, for example, as 2018-trends.html.

    Now we need a web server to process incoming http requests from users, and an application server for business logic. In order not to produce unnecessary essence, we will write a small program in the Go programming language, which will act as a web server and contain the blog code. To transfer user requests from the host program to the preprocessor, we will use the standard input stream (stdin), for serializing data we will use the popular format for serializing data - json.

    Script for processing input data:


    Код блога:

    main.go
    package main
    import (
    	"encoding/json"
    	"io/ioutil"
    	"net/http"
    	"os/exec"
    	"strings"
    	"github.com/labstack/echo"
    )
    func main() {
    	e := echo.New()
    	e.GET("/", index)
    	e.GET("/pages/:page", index)
    	e.Start(":8000")
    }
    func index(c echo.Context) error {
    	outData := struct {
    		Menu  []string `json:"menu"`
    		Pages []string `json:"pages"`
    	}{}
    	outData.Menu = make([]string, 0)
    	outData.Pages = make([]string, 0)
    	page := c.Param("page")
    	files, _ := ioutil.ReadDir("pages")
    	for _, file := range files {
    		if !file.IsDir() {
    			outData.Menu = append(outData.Menu, file.Name())
    		}
    		if page != "" && page == file.Name() {
    			fbody, _ := ioutil.ReadFile("pages" + "/" + file.Name())
    			outData.Pages = append(outData.Pages, string(fbody))
    		} else if page == "" {
    			fbody, _ := ioutil.ReadFile("pages" + "/" + file.Name())
    			outData.Pages = append(outData.Pages, string(fbody))
    		}
    	}
    	rendered := renderContent(outData)
    	return c.HTMLBlob(http.StatusOK, rendered)
    }
    func renderContent(input interface{}) []byte {
    	jsonInput, _ := json.Marshal(input)
    	tmplEngine := exec.Command("php", "-f", "index.php")
    	tmplEngine.Stdin = strings.NewReader(string(jsonInput))
    	rendered, _ := tmplEngine.Output()
    	return rendered
    }


    Теперь запускаем на исполнение программу через go run и делаем запрос на страницу через любой браузер, например таким образом:

    links2 http://localhost:8000

    Результат представлен на КДПВ.

    Пытливый читатель может заметить, что мы сильно теряем в производительности запуская на каждый запрос php процесс. Данный момент легко оптимизировать используя механизм pipes и запуская php процесс единожды в фоне, но это уже совсем другая история.

    Also popular now: