Fat-Free Frameworkを使用してブログを書く

念のため、これは翻訳です(HabraHabrインターフェースではこれに気付かない人が多いです)。

「Fat-Free」は英語から「Fat-free」と翻訳できます。これは、そのサイズ(55 KB)と速度に本当に驚かされるフレームワークです。



やっと簡単で高速なフレームワークを見つけました。 サイズはわずか55 KBのファイルに収まり、 公式Webサイトで学べる多くの機能を備えているので、繰り返しません。 代わりに、このフレームワークでブログを作成する方法を学ぶための短いチュートリアルを作成することにしました。

サーバーにPHP 5.3が必要です。 Ubuntu 11.04を使用してこのチュートリアルを作成しました。このバージョンのインストールは簡単です。 RHELまたはCentosで作業している場合は、最新バージョンのPHPを入手するためにIUS Community Projectに立ち寄ることをお勧めします。



設置



Fat-Free Frameworkをダウンロードしてください

Fat-Free Frameworkは、サイトのルートとサブディレクトリの両方で同様に機能します。 このチュートリアルでは別のサイトを作成する必要がないため、サブディレクトリを使用すると想定しています。

blogというフォルダーを作成し、フレームワークのコンテンツをそのフォルダーに解凍します。 次のようになります。







ディレクトリ階層を1レベル上に移動し、次のアクセス許可を設定します。



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





Apacheを使用している場合、mod_rewriteを有効にする必要があります。 .htaccessを変更し、RewriteBaseを調整してブログフォルダーを指すようにします。 例:RewriteBase / blog。



これで、サーバー上のブログフォルダーに移動して、次のページを表示できます。







(このページにアクセスするとすぐに、特別なキャッシュフォルダーが作成されます。心配する必要はありません)。



開始する



必要なのは既にFat-Free Frameworkにあります。



最初にメインページを編集し、データベース接続を作成しましょう。



index.phpファイルを開きます。 キャッシュオプションをコメントアウトし、デバッグレベルを設定して、開発を容易にします。



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





データベースへの接続を確立するには、 setコマンドとrunコマンドの間に次を追加します。



 F3::set('DB', new DB( 'mysql:host=localhost;port=3306;dbname=', '', '' ) );
      
      





すべてのユーザーインターフェイスファイルはuiディレクトリにあります。welcome.htmstyle.cssはホームページでデフォルトで使用されるだけなので、ここから削除できます。



ルーティング



フレームワークに要求メソッド(GET、POST、PUTなど)、要求のアドレス、およびこの要求に応答する方法を伝える必要があります。



ホームページのルーティング:



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





この名前のない関数には、ページを埋めるためのロジックが含まれます。



ブログ投稿を表示するには:



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





これにより、フレームワークはURIパラメーターを予期し、それを関数内のPHP変数に割り当てます。



管理者のルートは次のとおりです。



 //    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"]'); } );
      
      





同じ関数を使用してメッセージの追加と編集を処理するため、名前が付いていることに注意してください(他の関数に名前を付けることはできません)。



モデル



Fat-Free FrameworkのORMは、すべての汚い作業を行います-ディレクトリ、ファイル、コードはありません。



このチュートリアルに必要な2つのテーブルを作成するSQLクエリを次に示します。



何らかの理由で、HabraHabrはこのピースをペイントしたくありません-約 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');
      
      







訪問者向け



次に、Axonオブジェクトをインスタンス化して、結果の配列を取得する必要があります。 また、結果の値をarticles変数に設定します。



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





最後の2行を1つのF3 :: set( 'articles'、$ article-> afind());に結合できます。 しかし、便宜上2つ残しました。



テンプレートを使用するには、 uiフォルダーにlayout.htmlという名前で基本レイアウトファイルを作成する必要があります。



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





エンジンはテンプレート{{@ name}}を使用して変数の値を取得します。



ここで、 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>
      
      





テンプレートの準備ができたので、 index.phpのコードを完成させて表示できます。



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





アプリケーションを高速化するテンプレートは、PHPコードでエンジンによって再作成されます。



完全な例は次のようになります。



 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'); } );
      
      





次に、エントリの全文を含むページを作成する必要があります。



 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'); } );
      
      





ページテンプレートはblog_detail.htmlファイルにあります。



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





管理者向け



管理者のメインページには、エントリとメインページが表示されます。 このため、コードは同様です:



 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'); } );
      
      





テンプレートはadmin_home.htmlファイルに保存されます。



 <!--  ,   --> <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>
      
      





結果は次のようになります。







次に、 admin_edit.htmlファイルのエントリを編集および追加するためのフォームを作成します。



 <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>
      
      





メッセージ検証を表示する領域があることに注意してください。



ルートのコードは次のとおりです。



 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'); } );
      
      





さて、先ほど書いた編集機能を書きます。



  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'); }
      
      





認証



次の行を追加します。



 //         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は次のようになります。



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







テンプレートの前に行を追加::サービス:



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





以上です。 ユーザーをメインページにリダイレクトすることもできます。



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





まとめ



そのように、管理パネルとデータベースでブログを書くことができます。



完成した例をこちらからダウンロードできます-blog.zip







All Articles