Sei sulla pagina 1di 8

Fatfree framework

Esempi:
C:\xampp\htdocs\fatfree1\fatfree-master\public

Sommario
Esempi:.............................................................................................................................................................1
PHP tips............................................................................................................................................................2
Config files........................................................................................................................................................2
Costanti dinamiche...................................................................................................................................2
Variables...........................................................................................................................................................2
Autoload...........................................................................................................................................................2
Cache................................................................................................................................................................3
Routing.............................................................................................................................................................3
Map restAPI samples................................................................................................................................3
Cookie...............................................................................................................................................................3
Session..............................................................................................................................................................4
Database...........................................................................................................................................................4
Campi dinamici.........................................................................................................................................4
Sanification...............................................................................................................................................4
Mapper.....................................................................................................................................................4
Join...........................................................................................................................................................5
Dati in frontend........................................................................................................................................5
Upload..............................................................................................................................................................5
Multilanguage..................................................................................................................................................5
Views & Templates...........................................................................................................................................6
Token........................................................................................................................................................6
Direttive....................................................................................................................................................7
Filtri custom..............................................................................................................................................7
JS & CSS....................................................................................................................................................7
Log.................................................................................................................................................................... 7
Security.............................................................................................................................................................7
Unit test + mock...............................................................................................................................................7
n0nag0n > devtools..........................................................................................................................................8
1
Altre funzionalità in documentazione..............................................................................................................8

PHP tips
$test = ‘Test’;
Portare variabile in scope: $fw->route(‘GET /’, function($fw) use ($test)){ echo $test; }

Config files
Usa config.ini per dichiarare variabili [globals], come credenziali DB, cartelle AUTOLOAD, ENVIRONMENT...
Usa routes.ini per dichiarare le route.

$fw->config(__DIR__ . ‘/../config/config.ini’);
$fw->config(__DIR__ . ‘/../config/routes.ini’);

cli_routes.ini > es. contiene route per gli script cron

Altri file per: [maps] | [redirects] | [custom] | [custom callbacks] (es.


https://fatfreeframework.com/3.7/framework-variables#ConfigurationFiles)

Costanti dinamiche
index.php >
putenv(‘DB_PASS=123456’); define(‘ENVIRONMENT’, “DEVELOPMENT”);

config.ini >
DB_PASS = {{ getenv(‘DB_ PASS’) }}
DEBUG = {{ ENVIRONMENT === ‘DEVELOPMENT’ ? 3 : 0 }}

config.ini andrà in gitignore. Duplicarlo, cancellare dati riservati e rinominarlo come config_sample.ini che
invece finirà in git, ma farà da riferimento fac-simile, senza esporre dati riservati.

Variables
https://fatfreeframework.com/3.7/quick-reference oppure print_r($fw);

Ci sono variabili native che ci si può pescare ovunque si porti $fw: $fw->VERB = GET|POST
Si possono dichiarare variabili in $fw:
$fw->set(‘nome_sviluppatore’, ‘Mimmo’, cacheTime)
echo “Hello {$fw->get(‘nome_sviluppatore’)}”
$fw->mset(array(‘foo’=>’bar’, ‘baz’=>123)); //per dichiarazioni mutliple in una botta sola
$fw->clear('var');
$fw->exists(‘var’);
$fw->concat(‘a’,’b’); | $fw->copy(‘a’,’b’); | $fw->push(‘colors’,’red’); [pop,shift,unshift,merge]

Autoload
$f3->set('AUTOLOAD', '../app/');
es. $obj=new Gadgets\iPad;
2
F3 cerca in /var/www/html/ app /gadgets/ipad.php
si aspetta un file > namespace Gadgets; class iPad {}

Cache
$f3->CACHE = true;
$Cache = new Cache();
$Cache->exists('route-cache', $routes);
if (empty($routes)) {
...varie dichiarazioni di route
$routes = $f3->get('ROUTES');

$Cache->set('route-cache', $routes, 86400);


}
$f3->set('ROUTES', $routes);

Routing
Puoi dichiarare il metodo, l’url, eventuali parametri, l’alias da usare in giro nel codice, controller e action.

- routes.ini > GET|POST /entity/update/@entity_id/@new_value = EntityController->update


Parametri dalla route:
$fw->get(‘PARAMS.entity_id’)
$fw->route('GET /brew/@count', function($fw,$params) { echo $params['count']; });
- $fw->route('GET /login','Controller\Auth::login'); //per metodi statici
- $fw->route('GET /products/@action','Products->@action'); //per metodi dinamici
Altri esempi: C:\xampp\htdocs\fatfree1\fatfree-master\public

Redirect: $fw->reroute(‘/login’, false);


$fw->reroute('@beer_village_list(@country=Germany,@village=Rhine)');

Routing in CLI mode: https://fatfreeframework.com/3.7/routing-engine#RoutinginCLImode

Map restAPI samples


GET /api/v1/subscription/ list subscriptions
POST /api/v1/subscription/ create a subscription
GET /api/v1/subscription/:id/ get a subscription
PUT /api/v1/subscription/:id/ update a subscription
DELETE /api/v1/subscription/:id/ delete a subscription

Cookie
$fw->set(COOKIE.test, ‘Test’, secondsExpiration);
La variabile JAR contiene i parametri di default (sovrascrivibili) per la conservazione dei cookie:
$fw->JAR = [‘expires’ => time() + 500;]

3
Session
Base::instance()->SESSION[‘user_id’];

Database
Accertarsi di dichiarare la codifica dei caratteri nei parametri di connessione PDO.

$fw->DB->exec(“SELECT * FROM users WHERE email = ? AND role = ?”, [ $email, $role ]);
oppure
$fw->DB->exec(“SELECT * FROM users WHERE email = :email”, [ ‘:email’ => $f3->get('POST.email') ]);

Campi dinamici
$fieldname = $fw->GET[‘field_name’]; //verificare la legittimità
if($fieldname !== ‘ email’ && $fieldname !== ‘username’) die();
$sql = “SELECT * FROM users WHERE $fieldname = ...............”

var_dump($fw->DB->log());

Sanification
$post = $fw->clean($fw->POST);
oppure con il plugin n0nag0n > xss-filter: $post = Xss_Filter::fiilter(‘POST’);
oppure $f3->scrub($_GET,'p; br; span; div; a'); [rimuove tutti i tag HTML tranne quelli esplicitati]

Mapper
Nel controller:

READ | ->findone()
$user=new DB\SQL\Mapper($fw->DB,'users');
$user->load(array('userID=?','tarzan'));

LIST
$Entity = new DB\SQL\Mapper($fw->DB, ‘table_name’);
$results = $Entity->find($criteria, array('group'=>'foo', 'order'=>'foo,bar', 'limit'=>5, 'offset'=>0));
foreach() {
print_r $row->cast(); //converto obj in array
echo $row->id;
}

INSERT
$Entity = new DB\SQL\Mapper($fw->DB, ‘table_name’);
$Entity->field_name = ‘Lorem Ipsum’;
$Entity->save();

UPDATE
$Entity = new DB\SQL\Mapper($fw->DB, ‘table_name’);
$Entity->load([‘id=?’, $id]);
$Entity->field_name = ‘Lorem Ipsum’;
$Entity->save();
$Entity->reset(); //unload it
4
DELETE
$user->load(array('userID=? AND password=?','cheetah','ch1mp'));
$user->erase();

COUNT
$count = $Entity->count(array('visits>?',10));

EXIST
if ($Entity->dry()) $f3->error(404);

Scorciatoia
$Entity = new DB\SQL\Mapper($fw->DB, ‘table_name’);
$Entity->load(array('userID=123’));
if ($Entity->dry()) $f3->error(404);
$Entity->copyFrom(‘POST’); //i name devono coincidere con i campi della tabella
$Entity->save(); | ->update();

e l’inverso $Entity->copyTo('POST');
da usare nei template <input type="text" name="userID" value="{{ @POST.userID }}">

Join
Fat-free mapper non gestisce le JOIN. Vanno gestite con le VIEW lato database, mappando queste via
codice.
In alternativa si può installare il plugin ORM Cortex per gestire anche le JOIN lato codice.

Dati in frontend
$f3->set('result',$db->exec('SELECT brandName FROM wherever'));
echo Template::instance()->render('abc.htm');

Upload
Vedi: C:\Users\Rambo\Desktop\Fatfree framework 3.7 Video Tutorial Playlist\07 Security - File Uploads -
Fat-Free Framework 3.7 Tutorial - PHP.mp4

Multilanguage
Imposta un prefisso per le variabili di dizionario, tramite la costante PREFIX.
es. PREFIX=DICT. (punto compreso) [in config.ini]

Poi imposta le costanti LANGUAGE (lingua default) e LOCALES (path dei dizionari):
ENCODING='UTF-8'; [in config.ini]
LANGUAGE = 'it-IT'; [in config.ini] // se assente F3 lo ricava dal browser
LOCALES='/path/to/lexicons | 3600' [in config.ini] (numero per la cache)
FALLBACK='en' //lingua e dizionario se non ne trova altri

Creare un file per ogni dizionario:


(es. dict/en.php) >
return array(
'love'=>'I love F3',
5
'today'=>'Today is {0,date}',
'pi'=>'{0,number}',
'money'=>'Amount remaining: {0,number,currency}'
);

oppure (es. dict/de.ini) >


love = Ich liebe F3
today = Heute ist {0,date}
money = Restbetrag: {0,number,currency}
multiline = It's also possible to have language keys \
spread over multiple lines
[module.user.validation]
name.required = Please enter your name.
mail.invalid = This mail address is not valid.

Nei template basta richiamarli così:


<h1>{{ @love }}</h1>
<p>
{{ @today,time() | format }}.<br />
{{ @money,365.25 | format }}<br />
{{ @pi, 3.1415 | format }}
</p>

Views & Templates


$f3->set('ENCODING','ISO-8859-1');

echo \Template::instance()->render('template.htm');
<include href="header.htm" />
<include if="{{ count(@items) >= 2 }}" href="items.htm" />
<include href="{{ @content }}" /> // dove $fw->set('content','blog.htm');
<include href="{{ 'templates/layout/'.@content }}" />

<set d="abc" />


<include href="sub.htm" with="b=qlc, c='altro',d={{strtoupper($d)}}" /> // pass data to sub-template

Token
<p>Hello, {{ @name }}!</p>
<p>{{ @buddy[0] }}, {{ @buddy[1] }}, and {{ @buddy[2] }}</p>
{{ 2*(@page-1) }} {{ (int)765.29+1.2e3 }} {{ @active?'selected="selected"':'' }} {{ @obj->property }}

{{ @func('hello','world') }} // dove func è una funzione dichiarata in fw tramite set:


$f3->set('func', function($a,$b) {return $a.', '.$b;});

Quando si ha errore UNDEFINED VARIABLE o UNDEFINED INDEX, dichiarare sempre prima tutto nel codice,
anche in cason di valore nullo:
$f3->set('myVar',NULL); | $f3->set('myArray.myIndex', 'First Item')

6
Visto che con la costante ESCAPE a TRUE, tutto viene ripulito prima di essere stampato, nel caso di html
legittimo: {{ @html_content | raw }}

Direttive
https://fatfreeframework.com/3.7/quick-reference#TemplateDirectives

insert a route as an anchor >


$f3->route('GET @beer_village_list: /beer/@country/@village', 'Beer->byvillage');
<a href="{{ 'beer_village_list', 'country=Germany,village=Rhine' | alias }}">view list </a>

<exclude>
<p>A chunk of HTML we don't want displayed at the moment</p>
</exclude>

Altre direttive: check, true, false; repeat (group, key, value, counter)
Direttive e token si possono usare anche all’interno dei tag script.

Filtri custom
\Preview::instance()->filter('badwords','\Helper::instance()->badwords');

class Helper extends \Prefab {


function badwords($val) {
$bad_words = array("badword","jerk","damn");
$replacement_words = array("@#$@#", "j&*%", "da*@");
return str_ireplace($bad_words, $replacement_words, $val);
}
}

E quindi nel template: {{ @user_comment | badwords, uppercase }} // esempio di filtri combinati

JS & CSS
<link href="{{@BASE}}/ui/css/base.css" type="text/css" rel="stylesheet" />
<script src="{{@BASE}}/ui/js/base.css"></script>
<a href="{{@BASE}}/category-abc/article-xyz">read more</a>
<img src="{{@BASE}}/ui/img/img1.jpg" alt="Image 1" />

Log
$logger = new \Log('app-events.log');
$logger->write('User John logged in.');

Security
DOS + login page [https://fatfreeframework.com/3.7/optimization#BandwidthThrottling]

Unit test + mock


https://fatfreeframework.com/3.7/unit-testing

7
n0nag0n > devtools
Base_Controller contiene 2 metodi per stampare una response JSON o HTML

model > Mapper_shin contiene un metodo jsonSerialize che rende gli oggetti serializzabili
inoltre
$Entity = new DB\SQL\Mapper($fw->DB, ‘table_name’);
diventa
$Entity = new Entity($fw->DB);

models hanno 2 metodi beforeInsert e beforeUpdate con degli esempi per fare cose ripetitive: generare un
token, segnare la data di modifica in tabella, segnare l’utente che ha eseguito l’ultima modifica, ecc...

bin > unit-test lancia i test di unit-test-example.php

utils > Date + Template Helper (es. {{ @companis | length }})

Architecture

 app/config: db connections, routes, setup


 app/controller: controllers handle user request and process them
 app/model: entity and map db tables
 app/ui: html and template
 public: index.php, images, js, css
 app/utils: random class helpers (es. custom email class, special text formatter)
 app/log
 app/uploads
 app/tmp: cache folder
 vendor
 app/bin: eseguibili per unit test, cli, cron
 app/task: ???
 app/tests: unit test
 service.php: set DB, add Template filters...

Altre funzionalità in documentazione


 custom error handler
 db transactions
 navigation/pagination [https://fatfreeframework.com/3.7/databases#NavigationandPagination]
 table virtual field [https://fatfreeframework.com/3.7/databases#VirtualFields]
 estendi il DB Mapper [https://fatfreeframework.com/3.7/databases#SometimesItJustAin'tEnough]
 plugins [https://fatfreeframework.com/3.7/plug-ins]
 markdown [https://fatfreeframework.com/3.7/plug-ins#Markdown]
 file download [https://fatfreeframework.com/3.7/plug-ins#Web]
 fake-curl + fake-postman [https://fatfreeframework.com/3.7/plug-ins#Web]
 cache + minify [https://fatfreeframework.com/3.7/optimization]

Potrebbero piacerti anche