F3: a small PHP framework with great features



    I want to bring to your attention a lightweight PHP framework that I recently came across and which I immediately fell in love with.

    Fat-Free is somewhat similar to the famous Sinatra Ruby framework. The author of Fat-Free is obsessed with minimalism and code cleanliness, which positively affected this simple framework for developing a wide variety of applications.

    Fat-Free consists of a single file and weighs only 55KB. At the same time, the framework has such functionality: a specific and fairly convenient template engine, flexible caching, automatic spam protection, integrated tools for unit tests, and code profiler.

    It is so small and fast that it can even be used to control Web server traffic.

    It is also the only framework that protects your application from hotlinking and DoS attacks.


    It doesn't matter if you are a beginner or a professional PHP-programmer, Fat-Free is easy to use and powerful at the same time. It does not require installation or a clear directory structure. This framework allows you to write applications in both object-oriented and procedural styles. The Fat-Free philosophy and its approach to MVC architecture strive to minimize structural components, avoid complexity and balance between code elegance, application performance and programmer productivity.

    Fat-Free comes with plugins that will help expand the capabilities of the framework:

    • Auto-mapping ORM called Axon, which automatically determines the table fields in the database and creates the corresponding object variables for them;
    • M2 for working with MongoDB;
    • Form handler;
    • CAPTCHA generator;
    • JavaScript and CSS compressor;
    • Dynamic XML sitemap generator
    • Thumbnail and pseudo-image generator;
    • Identicons
    • Authorization
    • Flexible logging system;
    • Means for communication with other servers;
    • Processing ZIP archives;
    • Functions for working with the Google API, Twitter, Yahoo! and Akismet;
    • Support for multilingualism.


    Here is the file that displays the greeting on the main page:
    1. require_once 'path/to/F3.php';
    2. F3::route('GET /','home');
    3. function home() {
    4.     echo 'Hello, world!';
    5. }
    6. F3::run();
    7.  

    Getting to work


    Attention: for the framework to work, it needs a PHP version of at least 5.3 and an installed and configured mod_rewrite!

    In order not to make this guide too cumbersome, I decided to avoid writing a design and some obvious features for our simple guestbook application.

    To begin, create a database in any way convenient for you. Both SQLite / MySQL and MongoDB can act as databases. Since the application is exponential and simple, I choose SQLite.

    There is only one table in my guestbook.sqlite database - Comments , which contains the fields id , author and comment .

    Create the index.php file in the root of your application and rename the htaccess file to .htaccess (with a dot in front).

    Next, connect the main and only framework file in index.php and determine the path to the database:
    1. require_once ('F3 / F3.php'); // connect the framework
    2.  
    3. F3 :: set ('DB', array ('dsn' => 'sqlite: guestbook.sqlite')); / * Initialization of connection to the database.
    4. Attention: if you have version sqlite = 2, the DSN should look like this:
    5. 'dsn' => 'sqlite2: guestbook.sqlite'
    6.  * /

    In the first example, where the Hello World message is displayed, you saw one of the methods for processing routes (paths). In fact, there are several of them and you are free to choose:

    1. Route handler function - as in the first example. The second parameter of the F3 :: rote () method is the function that we describe in the same file, anywhere

    2. Anonymous function in the second parameter of the F3 :: rote () method : 3. The static class method in the same second parameter:
    1. require_once 'path/to/F3.php';
    2. F3::route('GET /',function () {
    3. echo 'Hello, world!';
    4. });
    5. F3::run();


    1. require_once 'path / to / F3.php';
    2. class MyClass {
    3.     public static function hello () {
    4.         echo 'Hello, world!';
    5.     }
    6. }
    7.  
    8.  
    9. F3 :: route ('GET /', 'MyClass :: hello');
    10. F3 :: run ();
    11.  

    4. The usual class method:
    1. require_once 'path / to / F3.php';
    2. class MyClass {
    3.     public function hello () {
    4.         echo 'Hello, world!';
    5.     }
    6. }
    7.  
    8. $ test = new MyClass;
    9.  
    10. F3 :: route ('GET /', array ($ test, 'hello'));
    11. F3 :: run ();
    12.  

    5. Finally, the handler may be a separate file located in an arbitrary directory with other such files. The directory with the handler files must be declared at the beginning of the index.php file, after which you can call the route handler file:
    1. //index.php:
    2. require_once 'path / to / F3.php';
    3. F3 :: set ('IMPORTS', 'yourpath');
    4. F3 :: route ('GET /', (: yourfile));
    5. F3 :: run ();
    6.  
    7. //yourpath/yourfile.php

    We continue the development of the guest book. Add the path to the plugin files in the index.php file - we need this to use the ORM called Axon, which comes with Fat-Free: Add the processing of the main page request in one of the above ways. I choose the first as the most visual. Here you go. Displaying comments is already working. You can proceed to the addition. But first, I want to talk a little about templates. The path to the templates is set in the same way as the others: You cannot pass a variable to a specific template. Variables in Fat-Free are set for the entire application. This is done using the already familiar static method:
    1. require_once('F3/F3.php');
    2. F3::set('AUTOLOAD','autoload/'); /*установка пути к плагинам.
    3. По умолчанию папка с плагинами называется autoload.
    4. Вы можете переименовать её и вынести за пределы корня сайта для большей безопасности.*/
    5. F3::set('DB',array('dsn'=>'sqlite:guestbook.sqlite')); 


    1. require_once('F3/F3.php');
    2. F3::set('AUTOLOAD','autoload/');
    3. F3::set('DB',array('dsn'=>'sqlite:guestbook.sqlite')); 
    4. F3::route('GET /','home');
    5. function home() {
    6. $comments = new Axon('comments'); //подключение к таблице comments БД
    7. $all_comments = $comments->find(); // Извлечение всех комментариев
    8. foreach ($all_comments as $comment) { /*  Обход всех результатов в массиве
    9.  и последуюющее их отображение. Напомню, что в данном примере
    10.  я пишу минимальный код без проверок на ошибки. */
    11. echo 'Автор: '.$comment['author'].'';
    12. echo 'Комментарий: '.$comment['comment'].'';
    13. }
    14. }




    1. F3::set('GUI','путь к шаблонам');


    1. F3::set('переменная','значение');

    Now this variable is available everywhere. In HTML code and in string form, its value is called as {@ variable}, in PHP code as:
    1. F3 :: get ('variable');

    To call the template, you should use the serve method: Thus, my application now looks like: In this example, we see how the Fat-Free template engine works: the loop processes a variable that contains all the comments. The next step is to add a comment form to the page. To do this, first describe the form itself in the form.html file located in the templates folder. In my case, the form looks like this. Next, you need to download this form inside the existing main page template in order to display the form under all comments. To do this, use the template tag inside the template.html template.
    1. F3::serve('template.html');


    1. //index.php:
    2.  
    3. require_once('F3/F3.php');
    4. F3::set('AUTOLOAD','autoload/');
    5. F3::set('DB',array('dsn'=>'sqlite:guestbook.sqlite'));
    6.  
    7. F3::route('GET /','home');
    8. function home() {
    9. $comments = new Axon('comments'); //подключение к таблице comments БД
    10. $all_comments = $comments->find(); // Извлечение всех комментариев
    11. F3::set('comments',$all_comments);
    12. F3::serve('template.html');
    13. }
    14.  
    15. ?>
    16.  
    17.  
    18.         

      {@comment.id}

    19.  




    1.  

    . Let me remind you that the form.html file must be in the same directory as template.html

    Now you should have a question - how to process the data sent? Everything is simple. Declare a handler in the index.php file for the POST method of the main page: Well, that’s it. The minimum guest book is ready. It took about 30 lines of code! Framework site Download the latest version of Fat-Free IRC support on irc.freenode.net: #fatfree The author of the framework is Bong Cosca. Here is his blog.
    1. require_once('F3/F3.php');
    2. F3::set('AUTOLOAD','autoload/');
    3. F3::set('DB',array('dsn'=>'sqlite:guestbook.sqlite'));
    4.  
    5. F3::route('GET /','home');
    6. function home() {
    7. $comments = new Axon('comments'); 
    8. $all_comments = $comments->find();
    9. F3::set('comments',$all_comments);
    10. F3::serve('template.html');
    11. }
    12.  
    13. F3::route('POST /','savecomment');
    14. function savecomment() {
    15. $comments = new Axon('comment');
    16. $comments->copyFrom('REQUEST'); /* Если названия полей формы
    17. соответствуют названиям полей таблицы,
    18. нет необходимости присваивать каждое значение отдельно.
    19. Можно воспользоваться удобной функцией copyFrom
    20. и получить данные из переменной $_REQUEST */
    21.  
    22. /* ...
    23. * тут добавьте обработку полученных данных
    24. */
    25.  
    26. $comments->save(); // добавление в базу данных
    27. $F3::reroute('/'); // переадресация на главную страницу
    28. }
    29. ?>








    Also popular now: