」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Flight 建立簡單的部落格 - 第 1 部分

使用 Flight 建立簡單的部落格 - 第 1 部分

發佈於2024-08-01
瀏覽:760

Hey everyone! I figured it was time to showcase some of the new features that have been added to the Flight Framework for PHP. Earlier this year the original creator of Flight Mike Cao graciously offered to transfer ownership of mikecao/flight over to a new Flight PHP organization. Since it's been moved we've added features like middleware, route grouping, DIC, and other features. This post will be a little longer, but it's just because I've included a lot of code examples so you can have the right context into how your blog will get built.

First off, let's just get this out of the way. Flight is meant to be a simple framework with a few bells and whistles. It will not compete with Laravel or Symfony or Yii or Cake or [fill in the blank]. This framework is really built towards simple to medium size projects. It also caters to those who don't like "magic" in their code that's hard to understand or train to. It's geared more towards developers who are just starting to branch into frameworks instead of raw PHP with a lot of random include statements.

tl;dr

Lots of cool features, nice simple implementation, blah blah blah here's the code. Go to part 2 for the cool stuff!

Installation

Let's use Composer to get this party started.

composer create-project flightphp/skeleton blog/
cd blog/

Configure your New Project

First thing to do is to go to the app/config/config.php file where we can put any config like API keys, database credentials, and other important credentials for our app. For this blog, we'll uncomment the line with file_path for our SQLite database path:

return [
    'database' => [
        // 'host' => 'localhost',
        // 'dbname' => 'dbname',
        // 'user' => 'user',
        // 'password' => 'password'
        'file_path' => __DIR__ . $ds . '..' . $ds . 'database.sqlite'
    ],
];

Create the Blog Database

Flight now comes with a command line utility called runway. This allows you to create custom commands for a plugin for Flight, or even for your own project.

As part of the skeleton, it comes with a SampleDatabaseCommand that will give us a starting point with this blog project we are creating.

Run the below command and it should populate your database for you!

php runway init:sample-db

Next we'll open up the app/config/services.php file and uncomment the line for SQLite.

// see how the $config variable references the config line we uncommented earlier?
$dsn = 'sqlite:' . $config['database']['file_path'];

Just to make sure we've got everything setup correctly, run composer start and then go to http://localhost:8000/ in your browser. You should see the following screen:

Default Home Page

You'll also notice in the corner you have a handy debug toolbar with some custom Flight panels to help you understand what's going on in your application. If you hover over the various items in the toolbar, you'll see a variety of hovers that you can click on to keep sticky on the page (more on that later).

Flight Tracy Extensions

Building the HTML Templates

Flight does come with a very basic HTML templating solution already in the framework. This is just fine for very simple sites or just to return a simple piece of HTML. It is recommended to use another templating platform such as Latte, Twig, or Blade. In this tutorial, we're going to use Latte because it is awesome and has no dependencies (you'll notice in Flight we do not like unnecessary dependencies)!

Go ahead and install Latte

composer require latte/latte

Add this to your services.php

$Latte = new \Latte\Engine;
$Latte->setTempDirectory(__DIR__ . '/../cache/');

// This is fun feature of Flight. You can remap some built in functions with the framework
// to your liking. In this case, we're remapping the Flight::render() method.
$app->map('render', function(string $templatePath, array $data = [], ?string $block = null) use ($app, $Latte) {
    $templatePath = __DIR__ . '/../views/'. $templatePath;
    $Latte->render($templatePath, $data, $block);
});

Now that we have a templating engine in place, we can create a base HTML file. Let's create a layout.latte file:


    
        
        
        
        
        {$page_title ? $page_title.' - '}Blog Built with Flight!
    
    
        {block content}{/block}
    

Active Record Database Class

Flight has a plugin for interacting with a database called Flight Active Record. This plugin helps you not write as much raw SQL in your apps (although sometimes it is more efficient to write a raw SQL query instead of forcing an active record/ORM/mapper to run it for you). Basically the active record extension helps you interact with rows within tables in your database: one row in a database can be mapped to an object in PHP (with autocomplete for the columns) saving time and sanity. Let's get it installed in our project.

composer require flightphp/active-record

Now you can use runway to create your active record classes automatically for you and it will create your properties as comments automatically (for autocomplete)!

First let's create the posts class. The first time you run this, it needs to setup the connection for the database.

$ php runway make:record posts
Database configuration not found. Please provide the following details:
Driver (mysql/pgsql/sqlite): sqlite
Database file path [database.sqlite]: app/database.sqlite
Username (for no username, press enter) []: 
Password (for no password, press enter) []: 
Writing database configuration to .runway-config.json
Creating directory app/records
Active Record successfully created at app/records/PostRecord.php

Now we'll create the comments record class:

$ php runway make:record comments

It's Time for your First Page!

Flight uses the MVC pattern. In order to create a new page you need to define a route in your routes.php file, create a new method in a controller, and then create the HTML file that the browser will serve. You can use runway to help you get started with a new controller class:

php runway make:controller Home

And you should see something similar to the following:

$ php runway make:controller Home
Controller successfully created at app/controllers/HomeController.php

If you go to app/controllers/HomeController.php go ahead and add this new method to your HomeController:

/**
 * Index
 * 
 * @return void
 */
public function index(): void
{
    $this->app->render('home.latte', [ 'page_title' => 'Home' ]);
}

And create a new file in app/views/home.latte and put in this code:

{extends 'layout.latte'}

{block content}

My Home Page

View My Blog!

{/block}

Finally let's change up the routes to the routes.php file. Go ahead and remove any code in the routes file that begins with $router-> and add a new route for your home router:

$router->get('/', \app\controllers\HomeController::class . '->index');

Make sure you run composer start so that your development server is up. If you go to http://localhost:8000/ in your browser, you should see something like this!

Flight Demo Home Page

Now we're cookin'!

Adding Routes for the Blog

Let's go ahead and add all the methods in your controller, routes, and html files. Let's start with adding the routes in your routes.php file:

// Blog
$router->group('/blog', function(Router $router) {

    // Posts
    $router->get('', \app\controllers\PostController::class . '->index');
    $router->get('/create', \app\controllers\PostController::class . '->create');
    $router->post('', \app\controllers\PostController::class . '->store');
    $router->get('/@id', \app\controllers\PostController::class . '->show');
    $router->get('/@id/edit', \app\controllers\PostController::class . '->edit');
    $router->post('/@id/edit', \app\controllers\PostController::class . '->update');
    $router->get('/@id/delete', \app\controllers\PostController::class . '->destroy');
});

So you'll notice we use a group() method here to group all the routes together that start with /blog. We could actually rewrite the routes like the following with the group() method and the same thing would happen:

// Posts
$router->get('/blog', \app\controllers\PostController::class . '->index');
$router->get('/blog/create', \app\controllers\PostController::class . '->create');

With the controller, first let's create an empty controller with runway:

php runway make:controller Post

You can copy the code below for your PostController.php:

app = $app;
    }

    /**
     * Index
     *
     * @return void
     */
    public function index(): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $posts = $PostRecord->order('id DESC')->findAll();
        $CommentRecord = new CommentRecord($this->app->db());
        foreach($posts as &$post) {
            $post->comments = $CommentRecord->eq('post_id', $post->id)->findAll();
        }
        $this->app->render('posts/index.latte', [ 'page_title' => 'Blog', 'posts' => $posts]);
    }

    /**
     * Create
     *
     * @return void
     */
    public function create(): void
    {
        $this->app->render('posts/create.latte', [ 'page_title' => 'Create Post']);
    }

    /**
     * Store
     *
     * @return void
     */
    public function store(): void
    {
        $postData = $this->app->request()->data;
        $PostRecord = new PostRecord($this->app->db());
        $PostRecord->title = $postData->title;
        $PostRecord->content = $postData->content;
        $PostRecord->username = $postData->username;
        $PostRecord->created_at = gmdate('Y-m-d H:i:s');
        $PostRecord->updated_at = null;
        $PostRecord->save();
        $this->app->redirect('/blog');
    }

    /**
     * Show
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function show(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $CommentRecord = new CommentRecord($this->app->db());
        $post->comments = $CommentRecord->eq('post_id', $post->id)->findAll();
        $this->app->render('posts/show.latte', [ 'page_title' => $post->title, 'post' => $post]);
    }

    /**
     * Edit
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function edit(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $this->app->render('posts/edit.latte', [ 'page_title' => 'Update Post', 'post' => $post]);
    }

    /**
     * Update
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function update(int $id): void
    {
        $postData = $this->app->request()->data;
        $PostRecord = new PostRecord($this->app->db());
        $PostRecord->find($id);
        $PostRecord->title = $postData->title;
        $PostRecord->content = $postData->content;
        $PostRecord->username = $postData->username;
        $PostRecord->updated_at = gmdate('Y-m-d H:i:s');
        $PostRecord->save();
        $this->app->redirect('/blog');
    }

    /**
     * Destroy
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function destroy(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $post->delete();
        $this->app->redirect('/blog');
    }
}

Let's kill some time and talk about a few things that are going on in the controller.

First off we are now using our new active record classes:

$PostRecord = new PostRecord($this->app->db());
$posts = $PostRecord->order('id DESC')->findAll();

We are injecting the database we setup in the services.php file above with $this->app->db();. Technically we could also just use Flight::db() as this points to the global $app variable.

Active Record classes are really helpful to simplify interactions with a database. We could rewrite the above in the following code:

$posts = $this->app->db()->fetchAll("SELECT * FROM posts ORDER BY id DESC");

This might not be the best example of how helpful an active record could be. But in part 2 I'll show you some hidden gems inside these classes that make it so much better than writing raw SQL.

Now let's talk HTML files. Here are the files we'll need for the post routes:

app/views/posts/index.latte

{extends '../layout.latte'}

{block content}

My Amazing Blog

Welcome to my blog!

Create a new post

{foreach $posts as $post} {first}

Recent Posts

{/first}

{$post->title}

By: {$post->username} on {$post->created_at|date:'d.m.Y G:i a'}

Comments: {count($post->comments)}

{$post->content|truncate:100}


Update - Delete {/foreach} {/block}

app/views/posts/show.latte

{extends '../layout.latte'}

{block content}
< Back to blog

{$post->title}

Created by: {$post->username} on {$post->created_at|date:'d.m.Y G:i a'}.

{$post->content|breakLines}

Last update: {$post->update_at|date:'d.m.Y G:i a'}.

Comments

{foreach $post->comments as $comment}

{$comment->username} on {$comment->created_at|date:'d.m.Y G:i a'}.

{$comment->content|breakLines}

Delete
{else}

No comments yet.

{/foreach}

Add comment

{/block}

app/views/posts/create.latte

{extends '../layout.latte'}

{block content}

Create a Post

{/block}

app/views/posts/edit.latte

{extends '../layout.latte'}

{block content}

Update a Post

{/block}

Create a new post

Now that we've got all the pieces in place, you should be able to load up your blog page, create a new post, see a post, and delete a post. You may have noticed we've included a comment form but the form doesn't actually work. We can fix that real quick! Let's create a controller with runway:

php runway make:controller Comment

Now you can make the CommentController.php look like the following:

app = $app;
    }

    /**
     * Store
     * 
     * @param int $id The post ID
     * 
     * @return void
     */
    public function store(int $id): void
    {
        $postData = $this->app->request()->data;
        $CommentRecord = new CommentRecord($this->app->db());
        $CommentRecord->post_id = $id;
        $CommentRecord->username = $postData->username;
        $CommentRecord->content = $postData->content;
        $CommentRecord->created_at = gmdate('Y-m-d H:i:s');
        $CommentRecord->updated_at = null;
        $CommentRecord->save();
        $this->app->redirect('/blog/' . $id);
    }

    /**
     * Destroy
     * 
     * @param int $id The post ID
     * @param int $comment_id The comment ID
     * 
     * @return void
     */
    public function destroy(int $id, int $comment_id): void
    {
        $CommentRecord = new CommentRecord($this->app->db());
        $CommentRecord->find($comment_id);
        $CommentRecord->delete();
        $this->app->redirect('/blog/' . $id);
    }

}

Now let's add a couple other routes in the group chunk of code in routes.php

// Blog
$router->group('/blog', function(Router $router) {

    // Posts

    // post routes...

    // Comments
    $router->post('/@id/comment', \app\controllers\CommentController::class . '->store');
    $router->get('/@id/comment/@comment_id/delete', \app\controllers\CommentController::class . '->destroy');
});

Conclusion (sort of)

With these two additions to the code, you have a fully functioning blog built with Flight! This got the job done and you now have a blog, but the code is somewhat clunky and could be improved to have some pretty nifty features like middleware, permissions, and writing less code! Hop over to part 2

Go ahead and leave any questions in comments below or join us in the chatroom!

If you want to see the final product with all the improvements here's the code!

版本聲明 本文轉載於:https://dev.to/n0nag0n/building-a-simple-blog-with-flight-part-1-4ap8?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-18
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內容...
    程式設計 發佈於2024-12-18
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-12-18
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-18
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-18
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-18
  • CSS3 轉場是否提供事件來偵測起點和終點?
    CSS3 轉場是否提供事件來偵測起點和終點?
    了解 CSS3 過渡事件CSS3 過渡允許在 Web 元素上實現流暢的動畫和視覺效果。為了增強使用者體驗並使操作與這些轉換同步,監控其進度非常重要。本文解決了 CSS3 是否提供事件來檢查過渡何時開始或結束的問題。 W3C CSS 過渡草案W3C CSS 過渡草案規定CSS 轉換會觸發對應的 DOM...
    程式設計 發佈於2024-12-18
  • Java 中可以手動釋放記憶體嗎?
    Java 中可以手動釋放記憶體嗎?
    Java 中的手動內存釋放與垃圾回收與C 不同,Java 採用託管內存框架來處理內存分配和釋放由垃圾收集器(GC) 自動執行。這種自動化方法可以提高記憶體利用率並防止困擾 C 程式的記憶體洩漏。 Java 中可以手動釋放記憶體嗎? 由於 Java 的記憶體管理是由GC,它沒有提供像 C 中的 fre...
    程式設計 發佈於2024-12-18
  • Java 1.6 中如何可靠地確定檔案是否為符號連結?
    Java 1.6 中如何可靠地確定檔案是否為符號連結?
    在 Java 1.6 中驗證符號連結確定符號連結的存在對於各種文件處理操作至關重要。在 Java 中,識別符號連結時需要考慮一些潛在問題,特別是在目錄遍歷的上下文中。 檢查符號連結的常見方法是比較文件的絕對路徑和規範路徑。規範路徑表示檔案的標準化路徑,而絕對路徑可能包括符號連結。傳統上,概念是如果這...
    程式設計 發佈於2024-12-17
  • 如何使背景顏色透明,同時保持文字不透明?
    如何使背景顏色透明,同時保持文字不透明?
    背景顏色的不透明度而不影響文本在Web 開發領域,實現透明度通常對於增強視覺吸引力和網站元素的功能。常見的要求是對 div 背景套用透明度,同時保留所包含文字的不透明度。這可能會帶來挑戰,特別是在確保跨瀏覽器相容性方面。 rgba 解決方案最有效且廣泛支持的解決方案是利用「RGBA」(紅、綠、藍、A...
    程式設計 發佈於2024-12-17
  • PHP 字串比較:`==`、`===` 或 `strcmp()` – 您應該使用哪個運算子?
    PHP 字串比較:`==`、`===` 或 `strcmp()` – 您應該使用哪個運算子?
    PHP 中的字串比較:'=='、'===' 或 'strcmp()'? PHP 中的字串比較PHP 可以使用不同的運算子來完成,例如「==」、「===」或「strcmp()」函數。此比較涉及檢查兩個字串是否相等。 '==' 與'...
    程式設計 發佈於2024-12-17
  • 如何自訂操作列的按鈕和外觀?
    如何自訂操作列的按鈕和外觀?
    自訂操作欄的按鈕和外觀要實現所需的自訂操作欄外觀,請考慮以下步驟: 1.建立自訂操作按鈕若要將圖片包含為按鈕,請透過擴充Button類別來定義自訂視圖。然後可以將此自訂視圖顯示在 ActionBar 上,如下所示:<Button android:id="@ id/my_cus...
    程式設計 發佈於2024-12-17
  • 介紹 Laravel 的履歷解析器/CV 解析器
    介紹 Laravel 的履歷解析器/CV 解析器
    照片由 Mohammad Rahmani 在 Unsplash 上拍攝 基於我們的 Resume/CV Parsing AI API 端點的流行,我們專門為您製作了一個專門的輕量級 Laravel 庫。 招募的未來:敏銳、精確且對 Laravel 友好 這個新套件可在 github...
    程式設計 發佈於2024-12-17
  • 如何在 PHP 中重新格式化日期以方便使用者顯示?
    如何在 PHP 中重新格式化日期以方便使用者顯示?
    在PHP 中重新格式化日期使用資料庫中儲存的日期時,通常需要重新格式化它們以便於使用者友好的顯示。對於以「2009-08-12」等格式儲存的日期尤其如此,人類本質上無法讀取這種格式。 為了解決這個問題,PHP 提供了各種工具,使您能夠輕鬆重新格式化日期。一種有效的方法是使用 DateTime 類,它...
    程式設計 發佈於2024-12-17
  • 為什麼我無法將元素新增到具有通配符泛型類型(`?extends Parent`)的 Java 集合中?
    為什麼我無法將元素新增到具有通配符泛型類型(`?extends Parent`)的 Java 集合中?
    型安與通配符泛型:了解禁止修飾符在Java 使用泛型集合時,通配符泛型的概念可以引入某些最初看起來可能違反直覺的限制。一個典型的例子是無法在具有通配符泛型類型的 Java 集合中新增值。 考慮以下程式碼片段:List<? extends Parent> list = ...; Paren...
    程式設計 發佈於2024-12-17

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3