Writing your blog with the Fat-Free Framework

Original author: Richard
  • Transfer
  • Tutorial
Just in case, this is a translation (many do not notice this in the HabrHabr interface).
“Fat-Free” can be translated from English as “Fat-free” - a framework that really impresses with its size (55 KB) and speed.


I finally found an easy and fast framework. It fits in a file of only 55Kb in size and has many features that you can learn about on its official website , so I won’t repeat it. Instead, I decided to make a short tutorial from which you will learn how to make your blog on this framework.
You will need PHP 5.3 on the server. I used Ubuntu 11.04 to write this tutorial, which easily installs this version. If you are working on RHEL or Centos, then I suggest you check out the IUS Community Project for the latest version of PHP.

Installation


Download Fat-Free Framework.
Fat-Free Framework works equally well both in the root of the site and in the subdirectory. I assume that you will use a subdirectory as you will not need to create a separate site for this tutorial.
Create a folder called blog and unzip the contents of the framework into it. It should look something like this:



Go up one level in the directory hierarchy and set the following permissions:

sudo chgrp -R www-data blog
sudo chmod -R 775 blog

If you are using Apache, then mod_rewrite must be enabled. Modify .htaccess and adjust RewriteBase so that it points to the blog folder. For example: RewriteBase / blog.

Now you can go to the blog folder on the server and see the following page:



(As soon as you visit this page, a special folder with a cache will be created - do not worry about it).

Start


All we need is already in the Fat-Free Framework.

Let's first edit the main page and create a database connection.

Open the index.php file . Comment out the caching option and set the debugging level to make it easier for you to develop:


To establish a database connection, add the following between the set and run commands :

F3::set('DB',
	new DB(
		'mysql:host=localhost;port=3306;dbname=ИмяВашейБазыДанных',
		'ИмяПользователя',
		'Пароль'
	)
);

All user interface files are in the ui directory - you can remove welcome.htm and style.css from here, since they are simply used by default by the home page.

Routing


You must tell the framework the request method (GET, POST, PUT, etc.), the address for the request, and how to respond to this request.

Route for the home page:

F3::route('GET /',
	function () {
	// делаем что-нибудь
	}
);

This nameless function will contain logic to fill the page.

To view a blog post:

F3::route('GET /view/@id',
	function () {
		$id = F3::get('PARAMS["id"]');
	}
);

This allows the framework to expect a URI parameter and assigns it to a PHP variable in the function.

Now the routes for the administrator:

// Главная страница администратора
F3::route('GET /admin',
	function () {	
	}
);
// Страница для добавления материала
F3::route('GET /admin/add',
	function() {
	}
);
// Для редактирования материала
F3::route('GET /admin/edit/@id',
	function() {
		$id = F3::get('PARAMS["id"]');
	}
);
// Служебная для принятия запросов
F3::route('POST /admin/edit/@id','edit');
F3::route('POST /admin/add','edit');
	function edit() {
	}
// Для удаления
F3::route('GET /admin/delete/@id',
	function() {
		$id = F3::get('PARAMS["id"]');
	}
);

Please note that we use the same function to process the addition and editing of messages, so it has a name (you can not give names to other functions).

Models


ORMs in the Fat-Free Framework do all the dirty work for you - no directories, files or code.

Here is an SQL query that will create the 2 tables necessary for this lesson:

For some reason, HabrHabr does not want to paint this piece - approx. perev.

CREATE DATABASE `blog` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `blog`;
CREATE TABLE IF NOT EXISTS `article` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `timestamp` datetime NOT NULL,
  `title` VARCHAR(128) NOT NULL,
  `summary` VARCHAR(128) NOT NULL,
  `content` text NOT NULL,
  `author` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `article` (`id`, `timestamp`, `title`, `summary`, `content`, `author`) VALUES
(1, '2011-07-28 02:03:14', 'Hello World!', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'Mr White'),
(2, '2011-07-28 02:03:14', 'More Hello World!', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'Mr Green');
CREATE TABLE IF NOT EXISTS `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`, `name`, `password`) VALUES
  ('1', 'admin', 'password');


For visitors


Now we need to instantiate the Axon object to get an array of results. We will also set the resulting value to the articles variable.

	$article=new Axon('article');
	$articles=$article->afind();
	F3::set('articles',$articles);

You could combine the last 2 lines into one F3 :: set ('articles', $ article-> afind ()); but for convenience I left two.

To use templates, you need to create a basic layout file in the ui folder with the name layout.html :

{{@html_title}}

The engine uses the template {{@ name}} to get the value of a variable.

Now create a template for the main page, which will be called blog_home.html :

Blog Titles

{{trim(@item['title'])}} by {{@item['author']}}

{{@item['summary']}}


Now that the template is ready, we can complete the code in index.php to display it:

	F3::set('content','blog_home.html');
	echo Template::serve('layout.html');

The template to speed up the application will be redone by the engine in php code.

A complete example would look like this:

F3::route('GET /',
	function () {
		F3::set('html_title','Home Page');
		$article=new Axon('article');
		F3::set('list',$article->afind());
		F3::set('content','blog_home.html');
		echo Template::serve('layout.html');	
	}
);

Now we need to make a page that will contain the full text of the entry:

F3::route('GET /view/@id',
	function () {
		$id = F3::get('PARAMS["id"]');
		// создаём объект Axon и ищем в нём наш id
		$article=new Axon('article');
		$article->load("id='$id'");
		// устанавливаем переменные для шаблона
		F3::set('html_title',$article->title);
		$article->copyTo('POST');
		// подключаем сам шаблон
		F3::set('content','blog_detail.html');
		echo Template::serve('layout.html');
	}
);

The page template will be in the blog_detail.html file :

{{@POST.title}}

Published: {{@POST.timestamp}} by {{@POST.author}}

{{@POST.content}}

Back to Homepage


For admin


The administrator’s main page will display entries as well as the main page. For this, the code is similar:

F3::route('GET /admin',
	function () {
		F3::set('html_title','My Blog Administration');
		$article=new Axon('article');
		$list=$article->afind();
		F3::set('list',$list);
		F3::set('content','admin_home.html');
		echo Template::serve('layout.html');	
	}
);

The template is stored in the admin_home.html file :

Панель администратора

Добавить запись

ЗаголовокДатаАвторУправление
{{@item['title']}}{{@item['timestamp']}}{{@item['author']}}ИзменитьУдалить

The result will be something like this:



Now create a form for editing and adding entries in the admin_edit.html file :

Edit

{{ @message }}










Note that there are areas for displaying message validation.

Now the code for the routes:

F3::route('GET /admin/add',
	function() {
		F3::set('html_title','My Blog Create');
		F3::set('content','admin_edit.html');
		echo Template::serve('layout.html');
	}
);
F3::route('GET /admin/edit/@id',
	function() {
		F3::set('html_title','My Blog Edit');
		$id = F3::get('PARAMS["id"]');
		$article=new Axon('article');
		$article->load("id='$id'");
		$article->copyTo('POST');
		F3::set('content','admin_edit.html');
		echo Template::serve('layout.html');
	}
);

Now we will write the editing function that was written about earlier:

	function edit() {
		// Reset previous error message, if any
		F3::clear('message');
		$id = F3::get('PARAMS["id"]');
		$article=new Axon('article');
		//load in the article, set new values then save
		//if we don't load it first Axon will do an insert instead of update when we use save command
		if ($id) $article->load("id='$id'");
		//overwrite with values just submitted
		$article->copyFrom('POST');
		//create a timestamp in MySQL format
		$article->timestamp=date("Y-m-d H:i:s");
		$article->save();
		// Return to admin home page, new blog entry should now be there
		F3::reroute('/admin');
	}

Authentication


Add the following lines:

// сообщаем фреймворку таблицу с пользователями и передаём значения
F3::set('AUTH',array('table'=>'user','id'=>'name','pw'=>'password'));
$auth = Auth::basic('sql');
// вход удачный
if ($auth) {
  // сохраняем в сессии
  F3::set('SESSION.user',$auth->name);
  // отображаем страницу администратора
  F3::set('content','admin_home.html');
} else {
  // вход неудачный
	F3::set('content','security.html');
}

security.html might look like this:

You must supply valid login details.



Add a line before Template :: serve:

if (!F3::get('SESSION.user')) F3::set('content','security.html');

That's all. You can also redirect the user to the main page:

if (!F3::get('SESSION.user')) F3::reroute('/');

Total


Just like that, you can write a blog with an admin panel and a database.

You can download the finished example here - blog.zip

Also popular now: