framework documentation - media.readthedocs.org · framework is a php framework aiming to help...

25
Framework Documentation Release 0.2 Kristijan Burnik Mar 09, 2017

Upload: others

Post on 21-Sep-2020

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework DocumentationRelease 0.2

Kristijan Burnik

Mar 09, 2017

Page 2: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate
Page 3: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Contents

1 Getting started 3

2 New project 5

3 Existing project 73.1 project-settings.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.2 project.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.3 The naming convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.4 How autoloading works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4 Templates 114.1 The template language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.2 The loop & Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.3 Context operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.4 Data transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164.6 Conditional expressions and branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164.7 Escaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184.8 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

5 Authors 19

6 Indices and tables 21

i

Page 4: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

ii

Page 5: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion withoutfocusing too much on boilerplate.

Most common web application infrastructure like REST APIs, DB abstraction via an Entity framework, routing, viewtemplates, writing unit tests and other features are available by using this framework.

In accord with the framework-scaffold project and framework-toolbox, a lot of development and deployment tasks aredone more easily.

Contents:

Contents 1

Page 6: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

2 Contents

Page 7: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 1

Getting started

If you’re planning on starting a new project using Framework, continue reading on starting a New project. If youwish to utilize the framework in an existing project skip to the Existing project section below.

3

Page 8: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

4 Chapter 1. Getting started

Page 9: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 2

New project

The recommended way to start a project is to check out the framework scaffold project and continue from there.

git clone https://github.com/kburnik/framwork-scaffold

You can find more documentation on setting up the scaffold in the project docs.

5

Page 10: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

6 Chapter 2. New project

Page 11: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 3

Existing project

Start by cloning the repository to a directory in your project. A good idea would be to have a third_party directoryand check it out there.

Depending on where you want the framework to be available, you will need to create the project-settings.php andproject.php files in the same directory.

project-settings.php

<?phpdefine('PROJECT_DIR', dirname(__FILE__));define('PATH_TO_FRAMEWORK', constant('PROJECT_DIR') . '/third_party/framework');

# REGIONAL.define('PROJECT_LANGUAGE', 'hr');define('PROJECT_TIMEZONE', 'Europe/Zagreb');

# NAME.define('PROJECT_NAME', 'myapp');define('PROJECT_TITLE', 'My App');define('PROJECT_DESCRIPTION', 'An empty project for scaffolding.');

# AUTHOR.define('PROJECT_AUTHOR', 'John Doe');

// Optional: if you want to use Framwork with a MySQL DB.# DB.define('PROJECT_MYSQL_USERNAME', 'myapp');define('PROJECT_MYSQL_PASSWORD', 'password');define('PROJECT_MYSQL_TEST_DATABASE', '');

7

Page 12: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

project.php

<?phpinclude_once(dirname(__FILE__) . '/project-settings.php');include_once(PATH_TO_FRAMEWORK . '/base/Base.php');

$project = Project::Create(constant('PROJECT_NAME'),constant('PROJECT_TITLE'),constant('PROJECT_AUTHOR'),constant('PROJECT_DIR'),constant('PROJECT_TIMEZONE'));

// Optional: if you want to use framework with a MySQL DB.if (defined('PROJECT_MYSQL_DATABASE')) {

$mysql = new MySQLProvider('localhost',constant('PROJECT_MYSQL_USERNAME'),constant('PROJECT_MYSQL_PASSWORD'),constant('PROJECT_MYSQL_DATABASE'));

$project->setQueriedDataProvider($mysql);SurogateDataDriver::SetRealDataDriver(new MySQLDataDriver());$mysql->connect();

}

$application = Application::getInstance();$application->Start();

Once you have the project.php file, you can include it in any of your scripts which want to use the Framework features.

This will register an autoloader class so you can reference other framework and your project classes without needingto include them.

The naming convention

Framework and projects built on top of it follow a simple naming convention which helps finding and including theclass when it’s first requested:

ClassName.php

<?phpclass ClassName {}

How autoloading works

Framework will automatically try to include a class if it’s not present in the execution environment. However, for theautoloader to know where to search you need to place an .include starting from your project root (PROJECT_DIR).

Example:

• project_dir/.include

• project_dir/project.php

• project_dir/project-settings.php

• project_dir/module/.include

8 Chapter 3. Existing project

Page 13: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

• project_dir/module/MyModuleClass.php

• project_dir/module/submodule/FramworkAutoloaderCannotSeeMe.php

• project_dir/public_html/index.php

In the index.php you just need to include the project.php and MyModuleClass will be available to the script as soon asyou use it.

project_dir/public_html/index.php

<?phpinclude_once(dirname(__FILE__) . '/../project.php');

# This will trigger the Framwork autoloader.$module = new MyModuleClass();$module->doStuff();

echo $module->getResults();

Framwork will start in the project root (project_dir) and recursively look for .include in every directory until it findsMyModuleClass.php.

Notice how our submodule direcotory does not have an .include file. This will cause the autoloader to skip the entiresubmodule directory when searching for the class FrameworkAutoLoaderCannotSeeMe and produce a regular PHPerror when referencing a non-existing class.

You can either include the class yourself or add the .include file to remedy this.

3.4. How autoloading works 9

Page 14: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

10 Chapter 3. Existing project

Page 15: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 4

Templates

Framework includes it’s very own template language for producing views. This is the preferred way to work withviews. Instead of having PHP files with a bunch of ‘<?php ?>’ blocks, you can write simple templates and keep thecode and view logic separate.

We can assume most data is stored in tables so we can have a simple table such as this one:

ID NAME SURNAME1 Jimmy Hendrix2 James Hetfield3 Dexter Holland

We can also assume that such a table is stored in a MySQL table, and a PHP script is fetching those rows to an arrayof a following structure:

<?php$data = array(

array("ID" => "1", "name" => "Jimmy", "surname" => "Hendrix"),array("ID" => "2", "name" => "James", "surname" => "Hetfield"),array("ID" => "3", "name" => "Dexter", "surname" => "Holland"),

);

In order to display this simple data structure as a table in an HTML document, we would need a generic function likethis:

<?phpfunction display_as_table($data) {if (!is_array($data) || count($data) == 0)return "No data";

// extract the keys (field names)$keys = array_keys( reset($data) );

// generate the table header$header="";foreach ( $keys as $field ) {

11

Page 16: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

$header .= "<th>{$field}</th>";}

// generate the table rows$rows="";foreach ( $data as $row ) {$rows.="<tr>";foreach ( $row as $field => $cell ) {

$rows.= "<td>{$cell}</td>";}$rows.="</tr>";

}

// construct the table with the header and rowsreturn "<table border='1'><thead><tr>{$header}</tr></thead><tbody>{$rows}</tbody>

</table>";

}

How ever useful this might seem, it’s not a good way to go, because not all data is simple as this, often you need toprovide links, styles and other view associated information... By expanding this function, you would be using a tonof parameters or objects to describe how you want your view to be displayed. It’s a very easy way to make your codehard to maintain.

A simpler and cleaner way would be to describe this view generating process in a separate view file namedstd.table.view.html:

<table border='1'><thead><tr>

$([*.0]) {<th>[#]</th>}</tr>

</thead><tbody>${<tr>

${ <td>[*]</td> }</tr>

}</tbody>

</table>

And whenever you want to produce a standard table, just make a simple call:

<?phpecho produceview('std.table.view.html', $data);

The template language

Let’s take a simpler example, we want to produce an ordered list:

1. One

12 Chapter 4. Templates

Page 17: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

2. Two

3. Three

<ol><li>One</li><li>Two</li><li>Three</li>

</ol>

So, here’s what we need to construct the view:

<?php// The view template.$template = '<ol> ${ <li>[*]</li> } </ol>';

// The data being presented by the view.$data = array("One", "Two", "Three");

// Output the view.echo produce( $template , $data );

Let’s now explain the template language.

First of all, the view expects some data to work with, that data is usually an array or a string. The data you pass tothe view via the produce or produceview function is called the root data. So our root data is array(“One”, “Two”,“Three”).

The other thing the view knows is it’s current value context. The current value context is denoted by [*] and the viewalways starts with the root data as it’s current value context.

The view also knows it’s current key context which is denoted by [#]. Root context however does not have a key (onlydata), so there is no such thing as a root key context.

In order to produce the list, we need to iterate over the root data values. We do so by writing:

$([*]){ The key value pair is [#] : [*] }.# ____ _________________________________# / \/ \# loop iterating expression# context [#] ==> key , [*] ==> value

Or we can omit the $([*]) part since the root context is our current context and just write:

${ The key value pair is [#] : [*] }

How this notation works is very similar to the PHP foreach statement. However, each time the view enters the ${ }loop it changes the key/value context so the meanings of [#] and [*] are different according to the position in the view(the loop level).

Let’s take another example:

$data = array("points" => array(array(10, 20), array(30, 40, 20), array(50, 60, 70)) ,"days" => array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday" )

);

We can use our imagination and write a template which displays this data:

4.1. The template language 13

Page 18: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

These are the points with X and Y values explicitly written out:$([points]){ Point at index [#] is ( [*.0] , [*.1] ) }

These are the same points with all available components:$([points]){ Point at index [#] is ( $[ , ]{[*]} ) }

These are the working days separated by a comma:$[, ]([days]){[*]}

This would produce to:

These are the points with X and Y values explicitly written out:Point at index 0 is ( 10 , 20 )Point at index 1 is ( 30 , 40 )Point at index 2 is ( 50 , 60 )

These are the same points with all available components:Point at index 0 is ( 10 , 20 )Point at index 1 is ( 30 , 40 , 20 )Point at index 2 is ( 50 , 60 , 70 )

These are the working days separated by a comma:Monday, Tuesday, Wednesday, Thursday, Friday

From this example we can cover three new features:

1. Iterating over a given key-value pair by defining the subcontext:

$([subcontext]) { ... }

2. The delimiter notation:

$[ delimiter ]([subcontext]){ ... }

3. The wrapping of the current value context:

/root$([*]) {

/root/firstlevel items$([*]){/root/firstlevel/secondlevel items

}}

The loop & Context

The best way to get comfortable with the looping and contexts would be through some examples. So let’s summarizeit with these:

# Pure iteration over current context.${ item_pattern }

# Pure iteration over current context + delimiter between outputs.$[delimiter]{ item_pattern }

14 Chapter 4. Templates

Page 19: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

# Iteration over given subcontext within the current context.$([subcontext]){ item_pattern }$([*.subcontext]){ item_pattern }

# Iteration over given subcontext within the current context + delimiter between→˓outputs.$[delimiter]([subcontext]){ item_pattern }

# Iteration of the upper level context (not applicable in root level).$([**]){ item_pattern }

Context operators

1. Key operator / index operator: [#]

2. Value operator: [*]

3. Parent context value operator: [**]

4. Count operator: [~]

5. Key+1 operator: [#+]

6. (Modulo 2) operator: [#%2]

7. Reverse index operator : [!#]

8. Revere index +1 operator : [!#+]

9. Subcontext operator: [context.subcontext]

10. Level up context value operator: [**], [**.**], ...

Data transformations

Let’s look at the following example:

Given a list of names, we want to print them all uppercased and comma separated.

<?php$data = array('John','Mike','Nicole','Jennifer');

The appropriate view template would be as follows:

$[, ]{[*:strtoupper]}

And the corresponding output would evaluate to:

JOHN, MIKE, NICOLE, JENNIFER

The lambda function in this example is the PHP built-in function strtoupper,

The syntax for data lambda-type data transformations on a context value is as follows:

[context<:lambda1<:lambda2<...<:lambdaN>>>>]

Let’s view some more examples:

4.3. Context operators 15

Page 20: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

['Y-m-d H:i:s':date]# output the date in the standard MySQL notation

[*:md5:strtoupper]# output the MD5 hash uppercased

[*:str_shuffle]# shuffle the letters of a string

Constants

PHP defined constant values can be printed in the following manner:

1. By using the literal expression and the PHP lambda function constant

${ ['MY_CONSTANT':constant] }

2. Using the shorthand operator @:

${ [@MY_CONSTANT] }

Example

Data and the constant:

<?phpdefine('SITEURL', '/path/to/siteroot');

$data = array(array('id' => 123, 'title' => 'Apple'),array('id' => 453, 'title' => 'Orange'),array('id' => 517, 'title' => 'Lemon'),

);

View template:

${<a href="[@SITEURL]/item/[id].html">[title]</a>}

Output:

<a href="/path/to/siteroot/item/123.html">Apple</a><a href="/path/to/siteroot/item/453.html">Orange</a><a href="/path/to/siteroot/item/517.html">Lemon</a>

Conditional expressions and branching

Often, you’ll want to display some data only if it satisfies a condition, or in some cases you’ll end up with two or moreoptions on how to display the data depending on it’s value or other conditions.

A typical scenario is a navigation menu which indicates the current active link:

16 Chapter 4. Templates

Page 21: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

<?php// navigation.php// include in all page serving scripts: i.e. index.php, about.php, ...

// get the name of the document being served$p = parse_url($_SERVER['REQUEST_URI']);$current_section = basename($p['path']);

// define the structure of the navgation and indicate the active link$nav = array('links' => array(

'index.php' => 'Home', 'about.php' => 'About', 'contact.php' => 'Contact us'

),'current' => $current_section

);

Example of a simple template for the navigation with the structure above.

<ul>$([links]){<li $?([**.current]==[#]){class="active"}><a href="/[#]">[*]</a></li>

}</ul>

The branching syntax (IF and IF-ELSE):

IF:

$?(<condition>){<output-if-true>}

IF-ELSE:

$?(<condition>){<output-if-true>}{<output-if-false>}

Good news! You can write more complex logic with logical operators!

All logical operators are same as in PHP:

1. ! – NOT

2. && – AND

3. || – OR

4. == – EQUAL

5. != – NOT EQUAL

6. < - LESS THAN <= - LESS THAN OR EQUAL > – GREATER THAN

7. >= – GREATER THAN OR EQUAL

Also arithmetic: +, -, *, /, %

Lambda functions are called in the context as follows [context:lambda1:lambda2]...

All terms in the boolean expression are either a [context] or a ‘literal’. Let’s look at a few examples:

<?php$data = array(

'a' => true,

4.6. Conditional expressions and branching 17

Page 22: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

'b' => true,'c' => false,'weather' => 'good','number' => 10,'maybe_empty' => '','elements' => array(10, 21, 30, 41, 50, 61, 70, 81, 90, 101)

);

$?([a] && [b]){ A and B }

$?(![a] && [c]) { not A and C }

$?([weather]=='good') { We're havin some good weather today } { Weather sucks today→˓man }

$?([number] > 5) { Over 5, to be exact it's a [number] } { Less than 5? Try again... }

$?([maybe_empty]) { Well it's not empty } { Yep, it's empty }

$?([weather]!='bad' && [number]>5) { It's your lucky day! }

$?([weather::strtoupper] == 'GOOD') { Still having GOOD weather }

The elements from 2nd to 5th:${$?([#+1]>=2 && [#+1]<=5) { [*] }

}

The elements with even values:${$?([*]%2==0) { [*] }

}

Escaping

Special characters $, [, ] you want to output need to be escaped with a backslash as follows: \$ , \[ , \].

You can also escape an entire block of text with the $<> quotation operator:

This is sensitive to special chars$<>This will always be printed as is.$<>This is sensitive to special chars

Notice that the “literal” block starts and ends with $<>

Comments

You can place a comment into your template with the following syntax:

$/* This is a comment. It's only present in the template file. */

Actual text being produced.

18 Chapter 4. Templates

Page 23: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 5

Authors

• Kristijan Burnik

19

Page 24: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

Framework Documentation, Release 0.2

20 Chapter 5. Authors

Page 25: Framework Documentation - media.readthedocs.org · Framework is a PHP framework aiming to help developers build complete websites in an MVC fashion without focusing too much on boilerplate

CHAPTER 6

Indices and tables

• genindex

• modindex

• search

21