Skip to content
g105b edited this page Nov 18, 2014 · 21 revisions

Adding logic to your pages

This tutorial will start at the point the Hello World tutorial left off: with a single HTML page outputting the traditional phrase "Hello, World!". The Hello World tutorial's completed code is hosted at http://github.com/BrightFlair/hello-world-tutorial.

Passing data from the page

Having PHP code inline within HTML is strictly forbidden, as it couples presentation view data with the computational business logic of your application.

At some point, it becomes necessary to bridge the gap between HTML and PHP: the web browser has already been built to do this through the use of forms. Let's update the index.html markup to include a simple HTML form that takes your name as a parameter, and is submitted using a button.

<!doctype html>

<h1>Hello, World!</h1>

<form>
    <label>
        Your name:
        <input name="your-name" />
    </label>
    <button>Submit</button>
</form>

The outcome of this tutorial will be to replace the word "World" with the supplied name. In order to replace "World", we will surround it in a span tag, making it easy to reference using standard DOM methods.

Let's change the h1 to wrap the placeholder word with a span:

<h1>Hello, <span>World</span>!</h1>

Page View & Page Logic

Pages that consist of HTML source (or other markup) are called Page Views, and strictly contain no PHP code.

Code that executes in context of a page is called Page Logic. To add Logic to a View, create a PHP script with the same name as the View. For example, the index.html view has its logic in the optional index.php script. The contents of the Logic script is a class definition with at least one method, go().

The go() method is called before the page is rendered and allows you to interact with the page via PHP and execute your required logic, calling other classes and functions where required.

The Page Logic's namespace is the Page directory prefixed with your application's namespace (by default, "App"). See below for an example.

Namespaces must be PSR-4 compliant.

The boilerplate Page Logic class for the index page looks like this:

src/page/index.php

<?php
namespace App\Page;

class Index extends \Gt\Page\Logic {

public function go() {
	// Your page logic here.
}

}#
Clone this wiki locally