📜 ⬆️ ⬇️

We write our blog with the framework of Fat-Free Framework

Just in case, this is a translation (many do not notice this in the interest of HabraHabra).
“Fat-Free” can be translated from English as “Fat-Free” - the framework really amazes with its size (55 KB) and speed.

I finally found a lightweight and fast framework. It fits into a file of only 55Kb in size and has many features that you can find out on its official website , so I will not repeat. Instead, I decided to make a small 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, on which this version is easily installed. If you work for RHEL or Centos, then I suggest you look at the IUS Community Project for the latest version of PHP.

Installation


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


')
Move 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 should be enabled. Change the .htaccess and adjust the RewriteBase so that it points to the folder with the blog. For example: RewriteBase / blog.

Already, you can go to the blog folder on the server and see this page:



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

Start


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

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

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

 <?php require __DIR__.'/lib/base.php'; //F3::set('CACHE',TRUE); F3::set('DEBUG',3); F3::set('UI','ui/'); F3::run(); ?> 

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 the default home page.

Routing


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

Route for homepage:

 F3::route('GET /', function () { //  - } ); 

This nameless function will contain the logic to fill the page.

To view a blog entry:

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

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

Now 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 (the remaining functions cannot be given names).

Models


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

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

HabraHabr for some reason does not want to paint this piece - approx. trans.

 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 create an instance of 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 merge 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 :

 <!DOCTYPE html> <html> <head> <title>{{@html_title}}</title> <meta charset='utf8' /> </head> <body> <F3:include href="{{@content}}"/> </body> </html> 

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

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

 <p>Blog Titles</p> <F3:repeat group="{{@list}}" value="{{@item}}"> <p><a href="view/{{@item['id']}}">{{trim(@item['title'])}}</a> by {{@item['author']}}</p> <p>{{@item['summary']}}</p> </F3:repeat> 

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 for speeding up the application will be converted into php code engine.

The full example will 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 have to make a page that will contain the full text of the post:

 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:

 <h1>{{@POST.title}}</h1> <p>Published: {{@POST.timestamp}} by {{@POST.author}}</p> {{@POST.content}} <p><a href='../'>Back to Homepage</a></p> 

For admin


On the main page of the administrator will be displayed entries as well as on the main. This 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:

 <!--  ,   --> <h1> </h1> <p><a href='admin/edit'> </a></p> <table> <thead> <tr> <th></th> <th></th> <th></th> <th colspan='2'></th> </tr> </thead> <tbody> <F3:repeat group="{{@list}}" value="{{@item}}"> <tr> <td>{{@item['title']}}</td> <td>{{@item['timestamp']}}</td> <td>{{@item['author']}}</td> <td><a href="admin/edit/{{@item['id']}}"></a></td> <td><a href="admin/delete/{{@item['id']}}"></a></td> </tr> </F3:repeat> </tbody> </table> 

The result will be something like this:



Now we will create a form for editing and adding records in the admin_edit.html file:

 <h1>Edit</h1> <form name="blog" method="post" action="{{ @BASE }}{{ @PARAMS.0 }}" > <F3:check if="{{ @message }}"> <p><span class="fail">{{ @message }}</span></p> </F3:check> <label for='title'>Title: </label><br /><input type="text" name="title" id="title" value="{{ htmlspecialchars(@POST.title) }}" size="60"/><br /> <label for='author'>Author: </label><br /><input type="text" name="author" id="author" value="{{ htmlspecialchars(@POST.author) }}" size="60"/><br /> <label for='summary'>Summary: </label><br /><textarea name="summary" id="summary" cols="60" rows="10">{{ htmlspecialchars(@POST.summary) }}</textarea><br /> <label for='content'>Content: </label><br /><textarea name="content" id="content" cols="60" rows="10">{{ htmlspecialchars(@POST.content) }}</textarea><br /> <input type="submit" value="Submit"/> </form> 

Please note that there are areas for displaying the message scan.

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 a function for editing, which was written 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("Ymd 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:

 <p>You must supply valid login details.</p> 


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


So just you can write a blog with admin panel and database.

You can download a ready-made example here - blog.zip

Source: https://habr.com/ru/post/135619/


All Articles